Introduction
Enums help you group related values under one name. They make your code easier to read and use.
Enums help you group related values under one name. They make your code easier to read and use.
enum EnumName { case case1 case case2 case case3 }
enum Direction { case north case south case east case west }
enum Light { case red, yellow, green }
enum Weekday { case monday case tuesday case wednesday case thursday case friday }
This program defines a Weather enum with four cases. It sets today's weather to sunny and uses a switch to print a message based on the weather.
enum Weather { case sunny case rainy case cloudy case windy } var todayWeather = Weather.sunny switch todayWeather { case .sunny: print("It's a bright and sunny day!") case .rainy: print("Don't forget your umbrella.") case .cloudy: print("It might rain later.") case .windy: print("Hold onto your hat!") }
You can use enums to make your code safer by limiting values to known options.
Use a dot (.) before case names when the enum type is already known, like .sunny.
Enums group related values under one name.
Each case is a possible value of the enum.
Use enums to write clearer and safer code.
enum in Swift?Direction with cases north, south, east, and west?enum, followed by the name and curly braces containing case declarations separated by commas.enum Direction { case north, south, east, west }. Others use invalid syntax.enum Light {
case red, yellow, green
}
let current = Light.red
switch current {
case .red:
print("Stop")
case .yellow:
print("Caution")
case .green:
print("Go")
}current is assigned Light.red.current.red and prints "Stop".enum Weather {
case sunny
case rainy
case windy
case
}case without a case name, which is invalid syntax.Planet with cases for mercury, venus, and earth. Then, write a function that returns a friendly message for each planet. Which code correctly implements this?case keyword; B misses it, so B is invalid.switch with dot syntax for cases and correct function signature. enum Planet { case mercury, venus, earth }
func message(planet: Planet) -> String {
if planet == mercury { return "Closest to the Sun" }
else if planet == venus { return "Second planet" }
else { return "Our home" }
} uses if-else without dot syntax (.mercury), causing compile error. enum Planet { case mercury, venus, earth }
func message(for planet: Planet) -> String {
switch planet {
case mercury: return "Closest to the Sun"
case venus: return "Second planet"
case earth: return "Our home"
}
} misses dot prefix in switch cases, causing error.Pass the test and this pattern moves unknown