<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 </div><div><br>Am 10.03.2016 um 22:55 schrieb Lammert Westerhoff via swift-evolution <<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a>>:<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. <br class="">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 .<br class=""><br class="">The ifPresent function is like the map 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 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: <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 func ifPresent(@noescape f: (Wrapped) throws -> Void) rethrows {<br class=""> _ = try 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>