Revisiting Optionals as Sequences

A few months ago I sent a pair of radars (22414579 nee 22448207 and 21961711) about Optional’s extant overloading of flatMap and how it doesn’t align with either the STL or the reasons given for the closing of both radars.

This issue behaves as intended based on the following:

Yes, we are aware that this overload of flatMap could be viewed as unconventional. Nevertheless, it is useful and fits the overload set in general, if you view Optional as a sequence of zero or one T. It resembles this overload, where the closure returns an arbitrary sequence:

extension SequenceType {
  public func flatMap<S : SequenceType>(transform: (Generator.Element) -> S) -> [S.Generator.Element]

The type checker ensures that there is no ambiguity between the two overloads, and we don't see a reason to give one of the overloads a different name (and force users to learn it, and differentiate between the two), since conceptually the operation is the same.

If Swift wishes to regard Optionals as collections with 1 or 0 elements, then I propose that it should reflect that thinking with additions to the standard library.

Possible changes include:

1) Remove or rename Optional’s flatMap.
This would cause a bit of breaking behavior, but it’s nothing some fixits couldn’t help with.

2) Add a SequenceType instance for Optional.
This kills 2 birds with 1 stone in that, if the radar rejection is to ring true, Optional should have a SequenceType instance in the STL, and such an instance would automatically come with its own proper overloading flatMap necessitating change 1.

Over in TypeLift land we’ve already implemented what we believe the SequenceType extensions should look like (\).