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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With