Search

Prefer Bare Enum Tags When That’s All You Need

Jeremy W. Sherman

1 min read

Oct 4, 2016

iOS

Prefer Bare Enum Tags When That’s All You Need

It’s great that you can associate data to Swift’s enums, but sometimes you don’t actually care about the data. It turns out the case statement syntax allows you to just use a bare tag name in that case, which beats the pants off case let .tag(_, _, _):.

Patterns Must Match Declaration Length

See, if you “don’t care”d all that data out, and then added another bit of associated data, your code would break, because you had the arity wrong: you have three “go away”s, and it expects four:

error: tuple pattern has the wrong length
for tuple type '(Int, Int, Int, Int)'

case .tag(_, _, _):
         ^

No Pattern, No Problem

If all you cared about was, “was this a .tag?”, then that’s straight up obnoxious. It’s still just .tag, and you flat-out don’t care what or how much data is bundled with it.

Good news: You can just write this:

case .tag:

Less visual noise, clearer expression of intention, and you’re now safe from arity changes.

Conclusion

If all you care about is the tag, and none of the associated data,
write:

case .tag:

and be on your merry way.

Juan Pablo Claude

Reviewer Big Nerd Ranch

During his tenure at BNR, Juan Pablo has taught bootcamps on macOS development, iOS development, Python, and Django. He has also participated in consulting projects in those areas. Juan Pablo is currently a Director of Technology focusing mainly on managing engineers and his interests include Machine Learning and Data Science.

Speak with a Nerd

Schedule a call today! Our team of Nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Not applicable? Click here to schedule a call.

Stay in Touch WITH Big Nerd Ranch News