Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call .map() on ImplicitlyUnwrappedOptional?

Tags:

swift

Optional<T> has map method.

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

When we want to convert Int? to UInt64?, we can:

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

Instead of:

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

Here, ImplicitlyUnwrappedOptional<T> has same method:

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

So I tried... and failed :(

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

Here is the question: How can I call this method?

like image 592
rintaro Avatar asked Dec 12 '14 11:12

rintaro


3 Answers

let i64Val = (iVal  as ImplicitlyUnwrappedOptional).map {UInt64($0)}
like image 82
Dániel Nagy Avatar answered Sep 21 '22 09:09

Dániel Nagy


let iVal:Int! = 42
let i64Val = (iVal as Int?).map { UInt64($0) }
like image 45
Airspeed Velocity Avatar answered Sep 19 '22 09:09

Airspeed Velocity


I think the error message clears it up: error: 'Int' does not have a member named 'map'. It says Int not Int! so the value is already unwrapped when trying to call a method.

So just use:

let iVal:Int! = 42
let i64Val = UInt64(iVal) 
like image 36
Kirsteins Avatar answered Sep 20 '22 09:09

Kirsteins