如何在ImplicitlyUnwrappedOptional上调用.map()?

时间:2014-12-12 11:16:52

标签: swift

Optional<T>map方法。

/// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
func map<U>(f: (T) -> U) -> U?

如果我们想将Int?转换为UInt64?,我们可以:

let iVal:Int? = 42
let i64Val = iVal.map { UInt64($0) }

而不是:

var i64Val:UInt64?
if let iVal = iVal {
    i64Val = UInt64(iVal)
}

此处,ImplicitlyUnwrappedOptional<T>使用相同的方法:

/// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
func map<U>(f: (T) -> U) -> U!

所以我试过......然后失败了:(

let iVal:Int! = 42
let i64Val = iVal.map { UInt64($0) } 
//           ^    ~~~  [!] error: 'Int' does not have a member named 'map'

以下是问题:如何调用此方法?

3 个答案:

答案 0 :(得分:4)

let i64Val = (iVal  as ImplicitlyUnwrappedOptional).map {UInt64($0)}

答案 1 :(得分:2)

let iVal:Int! = 42
let i64Val = (iVal as Int?).map { UInt64($0) }

答案 2 :(得分:1)

我认为错误消息会清除它:error: 'Int' does not have a member named 'map'。它说Int不是Int!所以在尝试调用方法时,该值已经解包。

所以只需使用:

let iVal:Int! = 42
let i64Val = UInt64(iVal)