Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using trailing closure in for-in loop

Tags:

swift

swift2

I'm using map() function of array in for-in loop like this:

let numbers = [2, 4, 6, 8, 10]

for doubled in numbers.map { $0 * 2 } // compile error
{
    print(doubled)
}

which produces compile error:

Use of unresolved identifier 'doubled'

However, if I put parenthesis for map() function, it works fine. i.e.

for doubled in numbers.map ({ $0 * 2 })
{
    print(doubled)
}

My question is, why wouldn't compiler differentiate code block of trailing function and loop, assuming this is causing the problem?

like image 996
Muhammad Hassan Avatar asked Jul 14 '16 13:07

Muhammad Hassan


1 Answers

This is because there would be ambiguity as to the context in which the trailing function should operate. An alternative syntax which works is:

let numbers = [2, 4, 6, 8, 10]

for doubled in (numbers.map { $0 * 2 }) // All good :)
{
    print(doubled)
}

I would say this is likely because the 'in' operator has a higher precedence than trailing functions.

It's up to you which you think is more readable.

like image 62
Lew Avatar answered Oct 04 '22 09:10

Lew