Why is it that this works:
var numbers = [20, 19, 7, 12]
numbers.map({
(number:Int)->Int in
if number % 2 == 0 {return number * 3}
else {return 0}
})
but not this:
var numbers = [20, 19, 7, 12]
numbers.map({
(number) in
if number % 2 == 0 {return number * 3}
else {return 0}
})
which gives the error message: "Cannot convert the expression's type 'Array<U>' to type 'U'"?
Apple's documentation says, "It is always possible to infer parameter types and return type when passing a closure to a function as an inline closure expression."
I can whittle your erroring example down to the simplest version:
let x = numbers.map({
(number) in
return number
})
Note that you're not actually using an inline closure expression. An inline version of what you're trying to accomplish would be:
numbers.map({$0 % 2 == 0 ? $0 * 3 : $0})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.