Tuesday, August 1, 2023

Swift Enum Pattern Matching With Extra Conditions

Natalia Panferova:

In this post we are going to explore how we can provide more precise conditions for pattern matching when working with enums in Swift. The most common use case is using switch statements with the where clause to get more control over case conditions. But we'll also look into using the where clause in for-in loops to avoid unnecessary extra iterations. And finally, we'll see how to add extra conditions in while loops and if-case statements when the where clause is not available.

I’ve always found Swift’s if case syntax confusing, because you have to put the constant first, and then you use =, which looks like an assignment, instead of ==. It makes more sense if you think about the variant Panferova shows, where there are associated values. Then it becomes if case let, and the order and operator are what you’d expect for a let. I generally write if anEnum == .aCase if I don’t need to bind any variables, but my recollection is that this either wasn’t supported or had issues in earlier versions of Swift.

Christian Tietze:

I believe there’s tremendous value in summaries like these to learn the Swift programming language and its syntax: these short summaries show a slice of different aspects of the language in close proximity.


It’s zooming in on where-clauses, and so the reader gets to know a different “view” into the syntax as a whole that is different from the book’s presentation.


2 Comments RSS · Twitter · Mastodon

Benjamin Esham

It looks like both of the links go to Christian’s article, instead of the first link going to Natalia’s article.

Leave a Comment