Function throws AND returns optional.. possible to conditionally unwrap in one line?

◇◆丶佛笑我妖孽 提交于 2019-11-28 13:42:27

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)).

I like Martin's answer but wanted to show another option:

if let value = (try? getSomething()) ?? nil {

}

This has the advantage of working outside of if, guard, or switch statements. The type specifier Any? isn't necessary but just included to show that it returns an optional:

let value: Any? = (try? getSomething()) ?? nil
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!