[swift-evolution] Add an ifPresent function to Optional
Thorsten Seitz
tseitz42 at icloud.com
Thu Mar 24 10:45:08 CDT 2016
> Am 24.03.2016 um 16:30 schrieb David Waite via swift-evolution <swift-evolution at swift.org>:
>
>
>>> On Mar 23, 2016, at 3:36 PM, Andrey Tarantsov via swift-evolution <swift-evolution at swift.org> wrote:
>>>
>>> * Are the current stdlib names for optional map and flatMap misleading?
>>
>> Not so much misleading, as being unfortunate when optionals and collections end up as neighbors in the code.
>>
>>
>>> * Are the current stdlib functions for optional closure application appropriate and sufficient?
>>>
>>> public func f1<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
>>> public func f2<U>(@noescape f: (Wrapped) throws -> U!) rethrows -> U!
>>> public func f3<U>(@noescape f: (Wrapped) throws -> U) rethrows -> Void
>>
>> I don't see why flatMap needs to be separate from map. It just does not make sense. I would only have
>>
>> public func f2<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
>>
>> and would call it "ifPresent", "then", "unwrap", "transform" or something like that.
>
> Optionals of Optionals are valid, and it would be ambiguous which would be returned from a map overloaded to allow both optional and non-optional transform functions. So, map always assumes the transform returns a non-optional, and if it returns an optional value (and that was not what you wanted) you have to flatten. Hence flatMap to combine the two steps.
Exactly.
And opposed to those the suggested ifPresent would have result type Void which is the whole point of it, i.e.
public func ifPresent(@noescape f: (Wrapped) throws -> Void) rethrows -> Void
Just to get the discussion back on track ;-)
-Thorsten
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160324/9373644c/attachment.html>
More information about the swift-evolution
mailing list