Using `map` and `flatMap` with implicit optionals


(Nicholas Maccharoli) #1

Since `ImplicitlyUnwrappedOptional` types can be unwrapped with an `if let`
or
accessed as an optional as in `foo?.bar` then why shouldn't there be
implementations of `map` or `flatMap` for use with IUO types?

I think having `map` and `flatMap` available on types marked with "!" would
be convenient
but is there a good reason why that isn't the case now?


(Tim Vermeulen) #2

This could cause problems when the underlying type also has a `map` or `flatMap` function:

let array: [Int]! = nil
array.map { $0 } // crash

Should this use Optional.map or Array.map?

As a workaround, you can simply do

let array: [Int]! = nil
(array as Optional).map { $0 } // nil

ยทยทยท

Since `ImplicitlyUnwrappedOptional` types can be unwrapped with an `if let` or
accessed as an optional as in `foo?.bar` then why shouldn't there be implementations of `map` or `flatMap` for use with IUO types?

I think having `map` and `flatMap` available on types marked with "!" would be convenient
but is there a good reason why that isn't the case now?