[swift-evolution] Add an ifPresent function to Optional

Dmitri Gribenko gribozavr at gmail.com
Mon Mar 14 20:29:06 CDT 2016


On Mon, Mar 14, 2016 at 5:51 PM,  <davesweeris at mac.com> wrote:
>
> On Mar 14, 2016, at 5:51 PM, Dmitri Gribenko via swift-evolution
> <swift-evolution at swift.org> wrote:
>
> Optional.map returns an Optional.
>
> Array.map returns an Array.
> Set.map returns an Array.
> <any other collection>.map returns an Array.
>
> I can't say that it is not valid to think about an Optional as a tiny
> collection, but as implemented in Swift, .map() does objectively
> behave differently...
>
> That behavior is, at least partially, because protocols don’t currently
> support this:
> protocol CollectionType {
>     typealias T
>     func map<U>(transform: T->U) -> Self<U> // error: Cannot specialize
> non-generic type 'Self'
> }

This feature is called higher-kinded types, and it is not planned for
design or implementation in the near future.

> I *think* I remember reading on here somewhere that the intent is to change
> map and flatMap to return “Self<U>" pretty much as soon as the language
> supports it.

As a standard library engineer I can with certainty that this is not
the plan.  We like the current formulation of map() that returns an
Array.

https://github.com/apple/swift/blob/master/docs/StdlibRationales.rst#high-order-functions-on-collections-return-arrays

I don't think that having HKTs in the language would change the rationale.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-evolution mailing list