swift - 仅当一个表达式中的可选值不为 nil 时才调用函数?

标签 swift option-type optional-binding

我知道可以这样做:

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/

相关文章:

arrays - 如何快速获取字符串数组中的最后 8 个字符?

ios - NSMutableArray 转换为自定义类型的快速数组

Swift 类型推断和类型检查问题

ios - 为什么类型 'UIView' 的值没有来自引用 UIView 变量的成员?

ios - 尝试从 URL 获取数据并获取控制台警告

ios - Swift 中的开关 - 开关中的 Case 标签应该至少有一个可执行语句

swift - 具有混合类型的 Nil 合并运算符

swift - 变量 'xxx' 从未发生突变,请考虑更改为 'let'

java - 使用 Guice 进行可选绑定(bind)以避免用户绑定(bind)

ios - 条件绑定(bind) : if let error – Initializer for conditional binding must have Optional type