Swift enumerations are similar like Java enum types in that they can declare functionality as well as the usual values.
To declare a basic enumeration we use the following syntax
enum Color {
case red
case white
case blue
// ... etc.
}
We can also declare using associated values, i.e.
enum Color: Int {
case red = 1
case white
case blue
// ... etc.
}
We can also declare enums as strings, for example
enum Color: String {
case red = "Red"
case white = "White"
case blue = "Blue"
// ... etc.
}
Enums can also have methods, so for example (a rather contrived example)
enum Color {
case red
case white
case blue
// ... etc.
func isRed() -> Bool {
self == .red // .red shows abbreviated syntax
}
}
We can also declare enum cases with associated data/properties, so for example
enum Device {
case phone(model: String)
case tablet(model: String)
case desktop(model: String)
}
let device = Device.phone("Samsung")
switch device {
case .phone(let model)
print("Phone: \(model)")
case .tablet(let model)
print("Tablet: \(model)")
case .desktop(let model)
print("Desktop: \(model)")
}
Recursive enum, where we might refer to the enum within the enum require the use of the keyword indirectcase. for example
enum Thing {
case value(String)
indirectcase thing(Thing)
}