[swift-evolution] Add an ifPresent function to Optional

Howard Lovatt howard.lovatt at gmail.com
Fri Mar 11 13:43:22 CST 2016

Why not make optional a SequenceType? This works really well in Scala and
provides the desired functionality via forEach.

On Friday, 11 March 2016, Lammert Westerhoff via swift-evolution <
swift-evolution at swift.org> wrote:

> Currently the Swift Optional doesn’t have an ifPresent function.
> This function is much like the map function except that the passed in
> function always returns Void. Almost the same can be done with
> the mapfunction, however the map function gives a compiler warning if it's
> result is unused. Also a map function can be ambiguous when there are
> multiple functions with the same name. The ifPresent will always pick the
> right function; i.e. the one returning Void and therefore is not ambiguous .
> The ifPresent function is like the map function very powerful. Some
> examples of its usage:
> let mapView: MKMapView = ... // some map view
> let annotation: MKAnnotation? = ... // some optional annotation
> annotation.ifPresent(mapView.addAnnotation)
> I also wrote a Blog Post about this topic in which I present it as an
> extension of Optional with some more examples where I find it very useful:
> https://swiftforward.wordpress.com/2015/12/04/add-ifpresent-to-swift-optionals/
> The implementation can be as simple as following:
> public func ifPresent(@noescape f: (Wrapped) throws -> Void) rethrows {
>    _ = try map(f)
> }
>> Lammert Westerhoff

-- Howard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160312/9500b648/attachment.html>

More information about the swift-evolution mailing list