M. Hassan M. Hassan - 4 months ago 22
Swift Question

Using trailing closure in for-in loop

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?

Lew Lew
Answer

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.