[swift-evolution] Add an ifPresent function to Optional
Kevin Lundberg
kevin at klundberg.com
Sat Mar 12 10:32:16 CST 2016
> +1 -- I've used the "an optional is a collection with max 1 element" rhetoric to explain map/flatMap, would be great if this was true instead of "morally true".
If optional were a sequence or collection, then could if let be considered a special case for this?:
for x in optionalX {
//...
}
I do like the idea that optional could be considered a collection, but I also worry about confusion in this case:
let a: [Int]? = [1,2,3]
for x in a {
// a is [1,2,3], not the expected iteration of 1 through 3
}
Today this does not compile and you are forced to unwrap the optional somehow. With this change I can see that someone may unexpectedly try this and be confused as to why the type of x is not what they expect.
>> @Dave,Yes, CollectionType would be better than SequenceType.
>>
>> On Saturday, 12 March 2016, Dave via swift-evolution<swift-evolution at swift.org(mailto:swift-evolution at swift.org)>wrote:
>> > +1.
>> >
>> > I’d go so far as to suggest that maybe Optional should conform to CollectionProtocol, since you can pretty easily think of an Optional as a collection that can’t have more than one element.
>> >
>> > - Dave Sweeris
>> >
>> > > On Mar 10, 2016, at 7:32 PM, Erica Sadun via swift-evolution<swift-evolution at swift.org(javascript:_e(%7B%7D,'cvml','swift-evolution at swift.org');)>wrote:
>> > >
>> > > While I'm not convinced of the utility or lack thereof, wouldn't it make more sense
>> > > to extend `forEach` to support optionals in a similar way that map and flapMap
>> > > currently do rather than introduce `ifPresent`?
>> > >
>> > > lety:Int? =1
>> > > letn:Int? =nil
>> > >
>> > > _=y.map({print($0) }) // works in current Swift
>> > > _=n.map({print($0) }) // ditto
>> > >
>> > >
>> > > y.forEach{ print($0) } // not currently a thing
>> > > n.forEach{ print($0) } // ditto
>> > >
>> > > Just spitballing here.
>> > >
>> > > -- E
>> > >
>> > > _______________________________________________
>> > > swift-evolution mailing list
>> > > swift-evolution at swift.org(javascript:_e(%7B%7D,'cvml','swift-evolution at swift.org');)
>> > > https://lists.swift.org/mailman/listinfo/swift-evolution
>> --
>> -- Howard.
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list