if case in Swift 2
Contents
If you ‘re trying to perform 2 nested switch
just to find the most suitable combination, then if case
in Swift 2 will save your day
Suppose I have a Maybe
(Maybe is similar to Optional)
1 |
public enum Maybe |
A naive solution could use nested switch
1 |
func combine |
Using if case
with multiple let
statements
1 |
func combine2 |
And enjoy
1 |
let ma = Maybe.Just(1) |
Here is the log if don’t believe me :D
1 |
(lldb) po ma |
Actually, there is another way, that is pattern matching against a tuple that contains both Maybe
1 |
func combine3 |
This is OK for a simple case like this. But I find if let
allows multiple statements, the following statement can access variable from the previous statements, which is nicer
Reference
- Match Me if you can: Swift Pattern Matching in Detail.
- Swift 2: Pattern Matching with “if case”
- Swift 2: Control Flow Pattern Matching Examples