我知道可以这样做:
let intValue: Int? = rawValue == nil ? Int(rawValue) : nil
或者甚至像这样:
var intValue: Int?
if let unwrappedRawValue = rawValue {
intValue = Int(unwrappedRawValue)
}
但是我正在寻找是否有一种方法可以在一个表达式中执行此操作,如下所示:
let intValue: Int? = Int(rawValue) // Where Int() is called only if rawValue is not nil
最佳答案
类似于Getting the count of an optional array as a string, or nil , 你可以使用 map()
可选
的方法:
/// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`.
@warn_unused_result
@rethrows public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
例子:
func foo(rawValue : UInt32?) -> Int? {
return rawValue.map { Int($0) }
}
foo(nil) // nil
foo(123) // 123
关于swift - 仅当一个表达式中的可选值不为 nil 时才调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192771/