[swift-evolution] Add an ifPresent function to Optional

Curtis Steckel steckel at squareup.com
Fri Mar 18 13:31:47 CDT 2016


Hello all,

Firstly, I would like to "throw my hat in the ring" in support of
Optional.ifPresent().

I have come across many opportunities to use such a utility function and
have used begun using a similar function in Java 8's Optional object very
frequently.

If others feel similarly, I would happily support or issue a proposal for
that single addition:

```
public enum Optional<Wrapped>: ... {
    ...
    /// If `self == nil` the function call is a no-op. Otherwise, calls
body(self!).
    public func ifPresent(@noescape body: (Wrapped) throws -> Void)
rethrows -> Void {
        switch self {
        case .None: return
        case .Some(let wrapped): try body(wrapped)
        }
    }
  ...
}
```

However, in regard to expanding Optional's implementation from a simple
enum with an associated value to a CollectionType, I feel that this may be
a bit of a distraction and could fall into a category of "premature
optimization."

I would argue that attempting to simplify the implementation semantics
should be considered a secondary goal to keeping the end-user (swift
developer) semantics easy to use and understand. The addition of an
abstract "boxed type" to organize methods that share names and conceptual
actions but different implementations may not be absolutely immediately
necessary or helpful.

On Mon, Mar 14, 2016 at 1:18 PM, Daniel Vollmer via swift-evolution <
swift-evolution at swift.org> wrote:

> Hi,
>
> > On 13 Mar 2016, at 18:04, Erica Sadun via swift-evolution <
> swift-evolution at swift.org> wrote:
> >
> > I am in favour of making optionals consistently act like 1-item-max
> collections.
>
> Why stop there? Why not make all non-optionals collections of one?
>
> I’m not convinced that making optionals conform to CollectionType actually
> improves matters: Yes, it may make the odd use here or there slightly more
> convenient, but at the cost of clarity IMO: Optionals have largely
> different set of concerns than collections, and having them suddenly
> inherit all CollectionType functionality and extensions doesn’t make their
> use (if it relies on them) any clearer, it obscures their “Optional”-ness
> instead.
>
>         Daniel.
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160318/c79cef28/attachment.html>


More information about the swift-evolution mailing list