Let’s look at a simple example.
enum SocialNetwork {
case facebook
case youTube
case whatsApp
case instagram
}
func post(to socialNetwork: SocialNetwork) {
switch socialNetwork {
case .facebook:
print("handle Facebook")
case .youTube:
print("handle YouTube")
case .whatsApp:
print("handle WhatsApp")
case .instagram:
print("handle Instagram")
}
}
post(to: .facebook) // prints "handle Facebook"
To check for a specific case on the SocialNetwork type is straightforward using the == equality operator.
func checkIsFacebook(socialNetwork: SocialNetwork) -> Bool {
return socialNetwork == .facebook
}
print(checkIsFacebook(socialNetwork: .facebook)) // prints true
print(checkIsFacebook(socialNetwork: .instagram)) // prints false
print(checkIsFacebook(socialNetwork: .youTube)) // prints false
Enums with associated values
Enumerations can have associated values, which are useful when you need to store data of some type along with the enum case. Taking the example from the Swift documentation, below is a Barcode enum that could be represented as UPC using a tuple of 4 integers, or as a QR code with a string.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
let upc: Barcode = .upc(8, 85909, 51226, 3)
let qrCode: Barcode = .qrCode("XXXXXXXXXXXXXXX")
If we try to write a similar function to check if a given Barcode is a UPC case, a compiler error will be shown.
func checkIsUPC(barCode: Barcode) -> Bool {
return barCode == Barcode.upc // 💥 Binary operator '==' cannot be applied to operands of type 'Barcode' and '(Int, Int, Int, Int) -> Barcode'
}
We can work around this using the slightly awkward syntax below.
func checkIsUPC(barCode: Barcode) -> Bool {
if case .upc = barCode {
return true
} else {
return false
}
}
print(checkIsUPC(barCode: upc)) // prints true
print(checkIsUPC(barCode: qrCode)) // prints false
And that’s it!