Updated for Xcode 14.2
Swift developers can use both switch
and if
to check multiple values in their code, and often there isn’t a hard reason why you should choose one rather than the other. That being said, there are three reasons why you might want to consider using switch
rather than if
:
switch
statements are exhaustive, which means you must either have a case
block for every possible value to check (e.g. all cases of an enum) or you must have a default
case. This isn’t true for if
and else if
, so you might accidentally miss a case.switch
to check a value for multiple possible results, that value will only be read once, whereas if you use if
it will be read multiple times. This becomes more important when you start using function calls, because some of these can be slow.switch
cases allow for advanced pattern matching that is unwieldy with if
.There’s one more situation, but it’s a little fuzzier: broadly speaking, if you want to check the same value for three or more possible states, you’ll find folks prefer to use switch
rather than if
for legibility purposes if nothing else – it becomes clearer that we’re checking the same value repeatedly, rather than writing different conditions.
PS: I’ve covered the fallthrough
keyword because it’s important to folks coming from other programming languages, but it’s fairly rare to see it used in Swift – don’t worry if you’re struggling to think up scenarios when it might be useful, because honestly most of the time it isn’t!
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.