Enums
Without Associated Type
-
Creation :
enum CompassPoint { case north case south case east case west }enum Planet { case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune } -
Access :
var directionToHead = CompassPoint.west-
Once
directionToHeadis declared as aCompassPoint, you can set it to a differentCompassPointvalue using a shorter dot syntax:directionToHead = .eastdirectionToHead = .south switch directionToHead { case .north: print("Lots of planets have a north") case .south: print("Watch out for penguins") case .east: print("Where the sun rises") case .west: print("Where the skies are blue") }
-
With Associated Type
-
Creation :
enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) }-
This definition doesn’t provide any actual
IntorStringvalues — it just defines the type of associated values that constants and variables can store when they’re equal toBarcode.upcorBarcode.qrCode.
var productBarcode = Barcode.upc(8, 85909, 51226, 3) productBarcode = .qrCode("ABCDEFGHIJKLMNOP") -
-
Access :
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).") } // Prints "QR code: ABCDEFGHIJKLMNOP."-
If all of the associated values for an enumeration case are extracted as constants, or if all are extracted as variables, you can place a single
letorvarannotation before the case name, for brevity:switch productBarcode { case let .upc(numberSystem, manufacturer, product, check): print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).") case let .qrCode(productCode): print("QR code: \(productCode).") } // Prints "QR code: ABCDEFGHIJKLMNOP."
-
Iterating
-
Swift exposes a collection of all the cases as an
allCasesproperty of the enumeration type if you writeCaseIterableafter the enumeration’s name.
enum Beverage: CaseIterable {
case coffee, tea, juice
}
let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) beverages available")
// Prints "3 beverages available"
for beverage in Beverage.allCases {
print(beverage)
}
// coffee
// tea
// juice
Default Value
-
Swift enumeration cases don’t have an integer value set by default.
-
In the
CompassPointexample above,north,south,eastandwestdon’t implicitly equal0,1,2and3. Instead, the different enumeration cases are values in their own right, with an explicitly defined type ofCompassPoint.
Other Topics
-
Raw Values.
-
Recursive Enumerations.