Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
This tutorial belongs to the Swift series
Enumerations are a way to group a set of different options, under a common name.
Example:
enum Animal {
case dog
case cat
case mouse
case horse
}
This Animal enum is now a type.
A type whose value can only be one of the cases listed.
If you define a variable of type Animal:
var animal: Animal
you can later decide which value to assign it using this syntax:
var animal: Animal
animal = .dog
We can use enumerations in control structures like switches:
enum Animal {
case dog
case cat
case mouse
case horse
}
let animal = Animal.dog
switch animal {
case .dog: print("dog")
case .cat: print("cat")
default: print("another animal")
}
Enumeration raw values can be strings, characters, or numbers.
You can also define an enum on a single line:
enum Animal {
case dog, cat, mouse, horse
}
You can also give the enumeration a raw value type, and assign a value of that type to each case:
enum Animal: Int {
case dog = 1
case cat = 2
case mouse = 3
case horse = 4
}
Once you have a variable, you can get this value using its rawValue property:
enum Animal: Int {
case dog = 1
case cat = 2
case mouse = 3
case horse = 4
}
var animal: Animal
animal = .dog
animal.rawValue //1
Enumerations are value types. This means they are copied when passed to a function, when returned from a function, and when we assign a variable that holds an enumeration to another variable.
Lessons in this unit:
| 0: | Introduction |
| 1: | Functions |
| 2: | Optionals and Nil |
| 3: | ▶︎ Enumerations |
| 4: | Structures |
| 5: | Classes |
| 6: | Objects |
| 7: | Protocols |
| 8: | Modules |