CaseIterable
Just discovered swift's CaseIterable which makes this sweet code possible:
let allCaseValues = MyEnum.allCases.map() {$0.rawValue}
Let’s say you’ve defined an enum like this one from the swift programming language guide:
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
Just adding CaseIterable to the declaration like this:
enum ASCIIControlCharacter: Character, CaseIterable {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
allows the use of the expression ASCIIControlCharacter.allCases, which returns the array
[ASCIIControlCharacter.tab,ASCIIControlCharacter.lineFeed, ASCIIControlCharacter.carriageReturn]
and using ASCIIControlCharacter.allCases.map {$0.rawValue} turns the array into an array of the raw values:
["\t”, "\n", "\r"]
In my case, I’m using an Enum for the CodingKeys for decoding a JSON object. Using
let allCaseValues = CodingKeys.allCases.map() {$0.rawValue}
gives me a list of the JSON object fields I’m expecting to be able to decode.