Use Associated Values in Swift Enumerations
Written by Team Kodeco
In addition to raw values, Swift enumerations can also have associated values. Associated values allow you to attach additional information to an enumeration case. This information can be of any type, different cases can have different types of associated values.
Here is an example of an enumeration with associated values:
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
In this example, the enumeration Barcode
has two cases, upc
and qrCode
. The upc
case has four associated values of type Int
, while the qrCode
case has one associated value of type String
.
You can use a switch statement to extract the associated values of an enumeration case:
let productBarcode = Barcode.upc(8, 85909, 51226, 3)
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
print("QR code: \(productCode).")
}
// Output: "UPC: 8, 85909, 51226, 3.