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?
let i64Val = (iVal as ImplicitlyUnwrappedOptional).map {UInt64($0)}
let iVal:Int! = 42
let i64Val = (iVal as Int?).map { UInt64($0) }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With