Jac*_*don 3 swift optional-binding option-type
我知道可以这样做:
let intValue: Int? = rawValue == nil ? Int(rawValue) : nil
Run Code Online (Sandbox Code Playgroud)
或者甚至像这样:
var intValue: Int?
if let unwrappedRawValue = rawValue {
intValue = Int(unwrappedRawValue)
}
Run Code Online (Sandbox Code Playgroud)
不过我想知道是否有一种方法可以在一个表达式中做到这一点,如下所示:
let intValue: Int? = Int(rawValue) // Where Int() is called only if rawValue is not nil
Run Code Online (Sandbox Code Playgroud)
与以字符串形式获取可选数组的计数或 nil类似,您可以使用map()
以下方法Optional:
/// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`.
@warn_unused_result
@rethrows public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
Run Code Online (Sandbox Code Playgroud)
例子:
func foo(rawValue : UInt32?) -> Int? {
return rawValue.map { Int($0) }
}
foo(nil) // nil
foo(123) // 123
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1202 次 |
| 最近记录: |