C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Let: We create a constant enum value that equals Size.Medium. We then test this against the ".Medium" value.
LetTip: With enums, we can omit the enum name, and just test against ".Medium," after the type variable type is known.
Result: The enum value equals ".Medium" so true is printed to the console with print().
Swift program that uses enum
enum Size {
case Small
case Medium
case Large
}
// Create a value of Size enum type.
let value = Size.Medium
// Test the value.
if value == .Medium {
print(true)
}
Output
true
Tip: The rawValue returns a value of the type specified in the enum. So here we get the Ints 0 and 1 from rawValue.
Swift program that uses rawValue with enum
// Specify a raw value type of Int on the enum.
enum Code: Int {
case Ruby, Python
}
// Access a case from the enum.
let c = Code.Ruby
// ... Access the rawValue from the enum case.
let raw = c.rawValue
print(raw)
// ... This case has a raw value 1 greater.
let raw2 = Code.Python.rawValue
print(raw2)
Output
0
1
Here: In the "if let" statement, we assign a variable to the optional's value. We then test the enum type.
Swift program that creates enum from rawValue
enum Animal: Int {
case Bird = 3
case Fish = 4
case Insect = 5
}
// Create Animal enum from a rawValue Int of 4.
if let temp = Animal(rawValue: 4) {
if temp == Animal.Fish {
// The rawValue is equal to Fish.
print(true)
print(temp.rawValue)
}
}
Output
true
4
Swift program that uses enum with switch
enum Importance {
case Low, Medium, High
}
// Assign to an enum value.
let value = Importance.High
// Switch on the enum value.
switch value {
case .Low:
print("Not important")
case .Medium:
print("Average")
case .High:
print("Do it now!")
default:
break
}
Output
Do it now!
Enum, switch warning:
main.swift:16:1: Default will never be executed
Swift program that uses enum argument, func
enum Importance {
case Low, Medium, High
}
func process(i: Importance) {
// Handle the enum argument in a func.
if i == .Low || i == .Medium {
print("Delay")
}
else {
print("Immediate")
}
}
// Call func with enum arguments.
process(i: Importance.Low)
process(i: Importance.Medium)
process(i: Importance.High)
Output
Delay
Delay
Immediate