[swift-evolution] Add an ifPresent function to Optional

Andrey Tarantsov andrey at tarantsov.com
Sun Mar 20 12:32:45 CDT 2016


-0.5 in general, on the basis of me never encountering a good use case for it.

> let annotation: MKAnnotation? = ... // some optional annotation
> annotation.ifPresent(mapView.addAnnotation)

if let annotation = produceAnnotation() {
    mapView.addAnnotation(annotation)
}


If annotation is a property...

if let annotation = annotation {
    mapView.addAnnotation(annotation)
}

...then:

1) it's still not so bad.

2) If you have too much optional state within a class, you may want to consider extracting a helper class / struct that deals with it. IMO, too many different state lifecycles within a class is a code smell, we shouldn't mask it with ifPresent.

Would love to see some compelling real-world use cases, though — maybe I'm missing something.

A.



More information about the swift-evolution mailing list