Minimize the map: error: cannot call 'map' with a list of arguments of type '((_) & # 8594; _)'

I do not understand why this works:

var arr = [4,5,6,7]

arr.map() {
    x in
    return  x + 2
}

while this one is not

arr.map() {
    x in
    var y = x + 2
    return y
}

with an error

Playground execution failed: MyPlayground.playground: 13: 5: error: cannot call a "map" with a list of arguments like '((_) → _)' arr.map () {

+4
source share
2 answers

The problem here is that there is an error message. In general, when you see something like cannot invoke .. with ...this, it means that the output of the compiler type just did not work.

. Swift , . :

arr.map() {
  x in
  return  x + 2
}

: return x + 2. :

arr.map() {
  x in
  var y = x + 2
  return y
}

(var y = x + 2), . , : , " map() ", : " , x y".

, , . return:

arr.map() {
  x in
  x + 2
}

:

arr.map() { $0 + 2 }

. , . (, , return , $0, x in - , ., , .)

: , , () :

arr.map { x in x + 2 }

@MartinR, :

let b: [Int] = arr.map { x in
  var y = x + 2
  return y 
}

. (, " " , )

+5

Swift . , y = x + 2 y Int. , Swift , .

:

arr.map() {
    x -> Int in
    var y = x + 2
    return y
}
+5

Source: https://habr.com/ru/post/1606976/


All Articles