How can I call .map () in ImplicitlyUnwrappedOptional?

Optional<T> has a map method.

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

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

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

Instead:

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

Here ImplicitlyUnwrappedOptional<T> has the same method:

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

So, I tried ... and could not: (

 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?

+5
source share
3 answers
 let i64Val = (iVal as ImplicitlyUnwrappedOptional).map {UInt64($0)} 
+4
source
 let iVal:Int! = 42 let i64Val = (iVal as Int?).map { UInt64($0) } 
+2
source

I think the error message will clear it: error: 'Int' does not have a member named 'map' . He says Int not Int! , so the value is already deployed when trying to call a method.

So just use:

 let iVal:Int! = 42 let i64Val = UInt64(iVal) 
+1
source

Source: https://habr.com/ru/post/1208880/


All Articles