<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body dir="auto"><div></div><div>+1</div><div>ifPresent is something I've used a lot in Java/Guava.</div><div>In Smalltalk we had at:ifPresent: for dictionary lookup which could then easily be simulated by lookup followed by ifPresent.</div><div><br></div><div>-Thorsten&nbsp;</div><div><br>Am 10.03.2016 um 22:55 schrieb Lammert Westerhoff via swift-evolution &lt;<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a>&gt;:<br><br></div><blockquote type="cite"><div><meta http-equiv="Content-Type" content="text/html charset=utf-8">Currently the Swift Optional doesn’t have an ifPresent function.&nbsp;<br class="">This function is much like the&nbsp;map&nbsp;function except that the passed in function always returns&nbsp;Void. Almost the same can be done with the&nbsp;mapfunction, however the&nbsp;map&nbsp;function gives a&nbsp;compiler warning if it's result is unused. Also a&nbsp;map&nbsp;function can be ambiguous when there are multiple functions with the same name. The&nbsp;ifPresent&nbsp;will always pick the right function; i.e.&nbsp;the one returning&nbsp;Void&nbsp;and therefore is not ambiguous .<br class=""><br class="">The&nbsp;ifPresent&nbsp;function is like the&nbsp;map&nbsp;function very powerful. Some examples of its usage:<br class=""><br class=""><div class="">let mapView: MKMapView = ... // some map view</div><div class="">let annotation: MKAnnotation? = ... // some optional annotation</div><div class="">annotation.ifPresent(mapView.addAnnotation)</div><br class="Apple-interchange-newline">I also wrote a&nbsp;Blog Post&nbsp;about this topic in which I present it as an extension of&nbsp;Optional with some more examples where I find it very useful:&nbsp;<a href="https://swiftforward.wordpress.com/2015/12/04/add-ifpresent-to-swift-optionals/" class="">https://swiftforward.wordpress.com/2015/12/04/add-ifpresent-to-swift-optionals/</a><div class=""><br class=""></div><div class="">The implementation can be as simple as following:</div><div class=""><br class="">public&nbsp;func&nbsp;ifPresent(@noescape&nbsp;f: (Wrapped) throws&nbsp;-&gt;&nbsp;Void) rethrows {<br class="">&nbsp; &nbsp;_&nbsp;=&nbsp;try&nbsp;map(f)<br class="">}</div><div class=""><br class=""></div><div class="">—</div><div class="">Lammert Westerhoff</div></div></blockquote><blockquote type="cite"><div><span>_______________________________________________</span><br><span>swift-evolution mailing list</span><br><span><a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a></span><br><span><a href="https://lists.swift.org/mailman/listinfo/swift-evolution">https://lists.swift.org/mailman/listinfo/swift-evolution</a></span><br></div></blockquote></body></html>