Even Swifter Enums
June 4, 2024
Swift's enums can have associated values, which are stored values that can be different for each instance of an enum, as well as raw values, & those can't change. Raw values must also conform to the RawRepresentable protocol, which means they have to be Strings, Ints, Floats, or whatever OptionSets are.
How to return other things as raw values isn't obvious, but help is at hand. Just like with structs and classes you can declare a function on an enum, & those can return any kind of value you'd like, including more complex types like a struct, whatever.
struct Possible {
let orange: Int,
bear: Int
}
enum fruit {
case apple,
pear
func raw() -> Possible {
switch self {
case .apple:
return Possible(orange: 1, bear: 2)
case .pear:
return Possible(orange: 3, bear: 4)
}
}
}
print(fruit.apple.raw()) // prints Possible(orange: 1, bear: 2)
This approach also makes it possible to use a more meaningful name than raw.
It also carries across to other languages without a concept of an enum's raw value. It was while using Rust on one of my occasional excursions to the language that the idea hit me. Rust doesn't have raw values for its enums but does allow function to be declared on them.