Add an ifPresent function to Optional


(Thorsten Seitz) #1

I’d argue against doing that, because when using map on specialized collections like Set or SortedCollection you usually do NOT want the result to be of the same type because this typically does not make sense, e.g.

let employees: Set = …

employees.map { $0.salary } // should NOT be a Set dropping equal salaries…

-Thorsten

···

Am 15. März 2016 um 01:51 schrieb Dave via swift-evolution swift-evolution@swift.org:

On Mar 14, 2016, at 5:51 PM, Dmitri Gribenko via swift-evolution swift-evolution@swift.org wrote:

Optional.map returns an Optional.

Array.map returns an Array.
Set.map returns an Array.
.map returns an Array.

I can’t say that it is not valid to think about an Optional as a tiny
collection, but as implemented in Swift, .map() does objectively
behave differently…
That behavior is, at least partially, because protocols don’t currently support this:

protocol CollectionType {

typealias T
func map<U>(transform: T->U) -> Self<U> // error: Cannot specialize non-generic type 'Self'

}

I think I remember reading on here somewhere that the intent is to change map and flatMap to return “Self" pretty much as soon as the language supports it. Someone from Apple would have to confirm that, though… my memory is quite hazy on the matter.