[swift-evolution] Add an ifPresent function to Optional

Adam Sharp adsharp at me.com
Thu Mar 10 20:11:22 CST 2016


A couple other ideas:

	// Not sure about the "if" prefix, but reads nicely
	foo.ifSome { print($0) }

	// Goes with other stdlib functions accepting closures, but perhaps less clear that the closure may not execute
	foo.withSome { print($0) }

–Adam

> On 11 Mar 2016, at 12:32 PM, Erica Sadun via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> 
>> On Mar 10, 2016, at 2:55 PM, Lammert Westerhoff via swift-evolution <swift-evolution at swift.org <mailto: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/ <https://swiftforward.wordpress.com/2015/12/04/add-ifpresent-to-swift-optionals/>
>> 
> 
> While I'm not convinced of the utility or lack thereof, wouldn't it make more sense 
> to extend `forEach` to support optionals in a similar way that map and flapMap 
> currently do rather than introduce `ifPresent`?
> 
> let y: Int? = 1
> let n: Int? = nil
> 
> _ = y.map({ print($0) }) // works in current Swift
> _ = n.map({ print($0) }) // ditto
> 
> y.forEach{ print($0) } // not currently a thing
> n.forEach{ print($0) } // ditto
> 
> Just spitballing here.
> 
> -- E
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160311/461aef14/attachment.html>


More information about the swift-evolution mailing list