Anonymous closing argument not contained in the closure

Why is this code not working?

func function (param1 : Int, param2 : Int) -> Int { return $0 + $1 } 

An error message is displayed:

Error: Anonymous closing argument not contained in the closing

+6
source share
3 answers

It seems you can only access parameters by number inside anonymous closures, not functions.

For instance:

 var sevenMultiplyedByThree: Int = { return $0 * 3 }(7) 

Also, this is only for anonymous parameters, so the following code will NOT work:

 var sevenMultiplyedByThree: Int = { (namedParameter : Int) -> Int in return $0 * 3 }(7) 
+4
source

I got it, access to parameters by their index is used when you do not have closing parameters with a name:

 var result = {$0 + 10}(5) result 
Result

now equal to 15

Unlike

 var result2 = { (param: Int) -> Int in return param + 10 }(5) result2 

it is not possible to use $ 0 instead of param because param is a parameter with a name .

+3
source

Swift automatically provides "Shorthand Argument", an anonymous argument to "$", only inside inline closures without declaring parameters

You declared a function that received param1 and param2. You can use it to send your function as a Block or add a closure. See the example below:

Your function announcement:

 func function (param1 : Int, param2 : Int) -> Int { return param1 + param2 } 

Call close function

 func getSum(sumFunction:(Int, Int) -> (Int)) -> (Int) { return sumFunction(3,5) } 

Using three possibilities:

  getSum(sumFunction: function) getSum { (param1, param2) -> (Int) in return param1 + param2 } getSum { return $0 + $1 } 

In the last getSum you have built-in closures without declaring parameters, only here you can use for $ 0 ..

$ - refer to the values ​​of the closure arguments with the names $ 0, $ 1, etc.

$ 0 = param1, $ 1 = param2

+3
source

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


All Articles