Enumeration in Swift: The Missing Manual

Apple’s official doc on Enumeration is missing a few valuable information. I hope this will be useful.

Named Values

Consider the example from Apple’s documentation:

enum Barcode {
 case UPCA(Int, Int, Int, Int)
 case QRCode(String)

What exactly are the four Int values stored for UPCA? Difficult to tell. You can assign names to them like this to make things clear.

enum Barcode {
 case UPCA(numberSystem: Int, manufacturerCode: Int, productCode: Int, check: Int)
 case QRCode(code: String)

When using the enum you need to specify the value names.

let barCode = Barcode.QRCode(code: "XYZ")

Deconstructing and Testing for a Match

To test for a match as well as obtain the values (deconstructing) in an enumerated variable you can use switch. This is already documented in the official docs. For example:

switch barCode {
case let .UPCA(numberSystem: _, manufacturerCode: _, productCode: prodCode, check: _):
  print("We have a UPCA with product code: \(prodCode)")
case let .QRCode(code: code):
  print("We have a QRCode with code: \(code)")

But switch statements are exhaustive. If you wish to just test for a specific match you can use “case let” with an “if” statement like this:

if case let .QRCode(code: code) = barCode {
  print("We have a QRCode with code: \(code)")
} else {
  print("It's not a QRCode")

Note: switch statement is more rigorous because it is exhaustive. If in future you add a new value to an enumeration the compiler will remind you to deal with it in every switch statement. The “if case let” syntax is not exhaustive. Use it carefully.

The break and fallthrough Keywords

Use the break keyword in a switch statement when you have nothing to do for a matched value. Below we only do something when the compass is pointing West.

enum CompassPoint {
 case North
 case South
 case East
 case West

let directionToHead = .South

switch directionToHead {
case .North: break
case .South: break
case .East: break
case .West:
 print("Where the skies are blue")

Use the fallthrough keyword if you wish to take the same action for multiple possible values. Here we warn the user about heading in a wrong direction unless she is heading West.

switch directionToHead {
case .North: fallthrough
case .South: fallthrough
case .East: print("You are heading in a wrong direction!")
case .West:
 print("Where the skies are blue")



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.