[swift-evolution] Brainstorming: Optional sugar inferred map

Paul Ossenbruggen possen at gmail.com
Sat Jan 30 23:24:03 CST 2016

This is what I came up with so far. As Joe points out, it needs delimiters for more complex maps. Assume this for the examples:

func doSomething(value: Int) -> Int {
    return value
let pf : Int? = 5
let pg : Int? = nil

for simple expressions you could do this which is a pretty big win:

let gf = pf? + 5

For cases where the expression should not call a function if a parameter is nil, I came up with this for syntactic sugar which has delimiters. Inside the brackets the variable name is unwrapped automatically and real name of the variable is used. rather than $0. It is a win over the if let approach:

// if let approach
let ff : Int? = nil
if let pf = pf {
 ff = doSomething(pf) 

// the delimited approach is:
let gf = pf?{ doSomething(pf) }  // pf not nil doSomething is called
let gg = pg?{ doSomething(pg) }  // pg is nil doSomething is not called.

gf -> 5
gg -> nil

// which is the equivalent of the map approach:
let ff = pf.map { doSomething($0) }
let fg = pg.map { doSomething($0) }

ff -> 5
fg -> nil

Assuming that this syntax is not a big enough win over the map version, This means that in this situation, you need to use map.. If doSomething() took an optional though you could do this, because doSomething would always be called.

let gf = doSomething(pf?)  // result is optional, could also omit “?"
let hf = doSomething(pf? + 5) // result is still an optional

- Paul
> On Jan 30, 2016, at 10:28 AM, Joe Groff <jgroff at apple.com> wrote:
>> On Jan 27, 2016, at 11:34 PM, Jacob Bandes-Storch via swift-evolution <swift-evolution at swift.org> wrote:
>> I've wanted this sort of thing a lot. It would also work for other functions, such as
>>    manager.doSomething(data: data, count: n?)
>> which is equivalent to
>>    n.map { manager.doSomething(data: data, count: $0) }
>> It might be hard to see exactly which operator/function applications such a thing applies to, if used in the context of a complex expression.
> Yes, this would be a major problem with this sort of feature. Without some explicit delimiter for the bounds of the map operation, you have either extremely subtle rules for defining the implicit bounds, or an exponential type-checking problem figuring it out from context. 
> -Joe

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160130/5f89752f/attachment.html>

More information about the swift-evolution mailing list