Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous closure argument not contained in a closure

Tags:

swift

Why doesn't this code work?

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

It produces an error:

Error: Anonymous closure argument not contained in a closure

like image 421
Raphael Oliveira Avatar asked Jun 02 '14 21:06

Raphael Oliveira


3 Answers

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

For example:

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

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

var sevenMultiplyedByThree: Int = {
    (namedParameter : Int) -> Int in
    return $0 * 3
}(7)
like image 119
phelgo Avatar answered Oct 20 '22 13:10

phelgo


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

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

Your function declaration:

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

Function that call closure

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

The three possibilities closures usage:

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

    getSum {
        return $0 + $1
    }

In the last getSum, you have inline closures without parameters declaration, Only here you can use for $0 ..

$ - refer to the values of the closure's arguments by the names $0, $1 and so on.

$0 = param1, $1 = param2

like image 8
Action Item Avatar answered Oct 20 '22 13:10

Action Item


I got it, accessing parameters by their index is used when you don't have the parameters of the closure named:

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

result

result now is 15

in contrast of

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

result2

it's not possible to use $0 instead of param because param is a named parameter.

like image 4
Raphael Oliveira Avatar answered Oct 20 '22 13:10

Raphael Oliveira