Enumerations
Enumerations, commonly known as enums, are a powerful feature in Swift that allow you to group related values together. Enums improve code readability and safety by making it easier to work with sets of related constants or values. This section will introduce you to the basics of using enums in Swift.
Declaring Enums
Enums are declared using the enum
keyword followed by the enumeration name and a set of cases enclosed in curly braces.
enum Direction {
case north
case south
case east
case west
}
Using Enums
Once an enum is declared, you can create a variable of that enum type and assign it one of the enum cases.
var currentDirection: Direction = .north
Switch Statement with Enums
Enums work exceptionally well with switch
statements, allowing you to handle each case concisely.
switch currentDirection {
case .north:
print("Heading north")
case .south:
print("Heading south")
case .east:
print("Heading east")
case .west:
print("Heading west")
}
Associated Values
Swift enums can store associated values, allowing you to attach additional information to each case.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
Using Associated Values
You can extract the associated values as part of a switch
statement.
let productBarcode = Barcode.upc(8, 85909, 51226, 3)
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
}
Raw Values
Enums can also have raw values, which are prepopulated values for each case.
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
You can initialize an enum from a raw value using the init?(rawValue:)
initializer.
let possiblePlanet = Planet(rawValue: 3) // Output: Optional(Planet.earth)
Conclusion
Enumerations in Swift offer a robust way to group related values, enhancing code readability and safety. They can be simple lists of cases, or they can be more complex with associated values and raw values. Mastering enums will make your Swift code more organized and maintainable.
Book a conversation with us for personalize training today!