Contents
  1. 1. Reference

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
2
3
4
public enum Maybe {
case Just(X)
case Nothing
}

A naive solution could use nested switch

1
2
3
4
5
6
7
8
9
10
11
12
13
func combine(ma: Maybe, mb: Maybe, f:(X,X)->X) -> Maybe {
switch ma {
case let .Just(valueA):
switch mb {
case let .Just(valueB):
return .Just(f(valueA,valueB))
case .Nothing:
return .Nothing
}
case .Nothing:
return .Nothing;
}
}

Using if case with multiple let statements

1
2
3
4
5
6
7
func combine2(ma: Maybe, mb: Maybe, f:(X,X)->X) -> Maybe {
if case let .Just(valueA) = ma, case let .Just(valueB) = mb {
return .Just(f(valueA,valueB))
} else {
return .Nothing
}
}

And enjoy

1
2
3
4
let ma = Maybe.Just(1)
let mb = Maybe.Just(2)
let mc = combine(ma, mb: mb, f: +)
let md = combine2(ma, mb: mb, f: +)

Here is the log if don’t believe me :D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(lldb) po ma
▿ Maybe
- Just : 1

(lldb) po mb
▿ Maybe
- Just : 2

(lldb) po mc
▿ Maybe
- Just : 3

(lldb) po md
▿ Maybe
- Just : 3

Actually, there is another way, that is pattern matching against a tuple that contains both Maybe

1
2
3
4
5
6
7
8
func combine3(ma: Maybe, mb: Maybe, f:(X,X)->X) -> Maybe {
switch (ma, mb) {
case let (.Just(valueA), .Just(valueB)):
return .Just(f(valueA, valueB))
case _:
return . Nothing
}
}

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

Contents
  1. 1. Reference