Swift Enum Pattern Matching With Extra Conditions
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
switchstatements with thewhereclause to get more control over case conditions. But we'll also look into using thewhereclause infor-inloops to avoid unnecessary extra iterations. And finally, we'll see how to add extra conditions inwhileloops andif-casestatements when thewhereclause 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.
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.
Previously:
- Pattern Matching on Swift Error Codes
- Swift’s “if case let” Syntax
- Restructuring Swift Condition Clauses
- Custom Swift Switch Matchers
2 Comments RSS · Twitter · Mastodon
It looks like both of the links go to Christian’s article, instead of the first link going to Natalia’s article.