Using trailing closure in for-in loop

前端 未结 3 1458
生来不讨喜
生来不讨喜 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:19

    The syntax is ambiguous (see dasblinkenlight's answer). For an alternative syntax:

    let numbers = [2, 4, 6, 8, 10]
    
    numbers.map { $0 * 2 }.forEach {
        print(doubled)
    }
    

    or

    let numbers = [2, 4, 6, 8, 10]
    let doubledNumbers = numbers.map { $0 * 2 }
    
    for doubled in doubledNumbers {
        print(doubled)
    }
    

提交回复
热议问题