Upcoming and OnDemand Webinars View full list

Prefer Bare Enum Tags When That’s All You Need

Jeremy Sherman

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.

Not Happy with Your Current App, or Digital Product?

Submit your event

Let's Discuss Your Project

Let's Discuss Your Project