Clicky

iOS Dev Nugget 241 Swift Enums with Labels

.

Need to run a code review on your codebase? Hire me

I like to use Swift enums to encode states and operations related to them since Swift enums are types that can have methods attached to them. I learnt one thing about enums recently, that enums with associated values can have labels. The Swift Programming Language book doesn't seem to mention this.

Eg. You have might an enum called Feeling with 3 cases.

enum Feeling {
    case happy(String, Int)
    case normal
    case unhappy(String, Int)
}

let theFeels1 = Feeling.normal
let theFeels2 = Feeling.happy("Because the weather is perfect", 2)

As you add more associated values, you start to lose track of what each value represents.

enum Feeling {
    case happy(String, String, Int, Int)
    case normal
    case unhappy(String, Int)
}

You can create a different struct for each case and pass in a struct instance.

Alternatively, you can add labels!

enum Feeling {
    case happy(reason: String, activity: String, numberOfPeopleWIthYou: Int, score: Int)
    case normal
    case unhappy(reason: String, score: Int)
}

Then you can/have to use labels when creating instances:

let theFeel = Feeling.happy(reason: "Because the weather is perfect", activity: "grocery shopping", numberOfPeopleWIthYou: 0, score: 2)

They look better when you dump() them:

dump(theFeel)

__lldb_expr_86.Feeling.happy
  ▿ happy: (4 elements)
    - reason: "Because the weather is perfect"
    - activity: "grocery shopping"
    - numberOfPeopleWIthYou: 0
    - score: 2

You can (optionally) use the labels in a switch statement if you want to. It checks that the label matches. Notice that score doesn't use a label.

switch theFeel {
case .happy(reason: let reason, _, _, let score):
    print("happy \(reason) with score: \(score)")
case .unhappy:
    print("unhappy")
case .normal:
    print("normal")
}

Interestingly, you don't have to have labels for every value, but I can't think of a good reason to use this:

enum Feeling {
    case happy(reason: String, String, Int, score: Int)
    case normal
    case unhappy(reason: String, score: Int)
}


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues