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

rin*_*aro 5 swift

Optional<T>map方法.

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

当我们想要转换Int?UInt64?,我们可以:

let iVal:Int? = 42
let i64Val = iVal.map { UInt64($0) }
Run Code Online (Sandbox Code Playgroud)

代替:

var i64Val:UInt64?
if let iVal = iVal {
    i64Val = UInt64(iVal)
}
Run Code Online (Sandbox Code Playgroud)

在这里,ImplicitlyUnwrappedOptional<T>有相同的方法:

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

所以我试过......但失败了:(

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

这是一个问题:我怎么称呼这种方法?

Dán*_*agy 4

let i64Val = (iVal  as ImplicitlyUnwrappedOptional).map {UInt64($0)}
Run Code Online (Sandbox Code Playgroud)