Using trailing closure in for-in loop

前端 未结 3 1456
生来不讨喜
生来不讨喜 2021-02-20 13:42

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
         


        
3条回答
  •  滥情空心
    2021-02-20 14:28

    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.

提交回复
热议问题