Skip to content

Instantly share code, notes, and snippets.

@vesic
Created December 1, 2022 19:15
Show Gist options
  • Save vesic/fec58b5c525b3e7f3af40ab4bf8331e3 to your computer and use it in GitHub Desktop.
Save vesic/fec58b5c525b3e7f3af40ab4bf8331e3 to your computer and use it in GitHub Desktop.
// User defined type
// Restricted to finite set of related or like values
// Safe and clean
// Compile time check
// Expressing algorithms naturally
// Monday, Tuesday, Wednesday...
// Instead of 1, 2, 3...
enum Color {
case red, green, blue
}
let color:Color = .red
if color == .red {
print("Color is red")
} else {
print("Color is not red")
}
switch color {
case .red:
print("Color is red")
case .green:
print("Color is green")
case .blue:
print("Color is blue")
}
// Powerful and flexible
// Can do most everything structure can do
// No values assign by default
// By decorating enum name you can associate raw values
// Can be all numeric types, string and char
//enum Level: Int {
// case low = 1
// case medium = 2
// case high = 3
//}
enum Level: Int {
case low = 1
case medium
case high // 3
}
let currentLevel: Level = .low
currentLevel.rawValue
enum Result {
case success(value: Int)
case error(message: String)
}
let result: Result = .success(value: 100)
switch result {
case .success(let newValue):
print("New value is \(newValue)")
case .error(let error):
print(error)
}
enum Day {
case sunday, monday, tuesday, wednesday, thursday, friday, saturday
func isWeekday() -> Bool {
switch self {
case .saturday, .sunday:
return false
default:
return true
}
}
}
let day: Day = .monday
if day.isWeekday() {
print("Workweek")
} else {
print("Weekend")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment