Swift: Ambiguous reference to member 'map'

后端 未结 2 1314
误落风尘
误落风尘 2021-01-22 03:49

I\'m reading \"The swift programming language 4.2\". In the beginning chapter, page 23, I have this following requirement:

Rewrite the closure to return z

2条回答
  •  清酒与你
    2021-01-22 04:20

    Rather than annotating the parameter type you have to specify the return type of the closure

    let myArray = [1, 2, 3, 4, 5] // You don't even need to annotate the array, the compiler knows the type.
    
    let result = myArray.map({ number -> Int in
        if number % 2 != 0 {
            return 0
        } else {
            return number
        }
    })
    

    Or with trailing closure syntax and shorthand argument names. In this case the compiler can infer everything

    let result = myArray.map { $0 % 2 != 0 ? 0 : $0 }
    

提交回复
热议问题