Update: As of Swift 5, try?
applied to an optional expression does not add another level of optionality, so that a “simple” optional binding is sufficient. It succeeds if the function did not throw an error and did not return nil
. val
is then bound to the unwrapped result:
if let val = try? getSomething() {
// ...
}
(Previous answer for Swift ≤ 4:) If a function throws and returns an optional
func getSomething() throws -> Value? { ... }
then try? getSomething()
returns a "double optional" of the
type Value??
and you have to unwrap twice:
if let optval = try? getSomething(), let val = optval {
}
Here the first binding let optval = ...
succeeds if the function did
not throw, and the second binding let val = optval
succeeds
if the return value is not nil
.
This can be shortened with case let
pattern matching to
if case let val?? = try? getSomething() {
}
where val??
is a shortcut for .some(.some(val))
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…