Raphael Oliveira
Raphael Oliveira

Reputation: 7841

Anonymous closure argument not contained in a closure

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

Upvotes: 16

Views: 26272

Answers (3)

Action Item
Action Item

Reputation: 99

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

Upvotes: 8

phelgo
phelgo

Reputation: 111

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)

Upvotes: 11

Raphael Oliveira
Raphael Oliveira

Reputation: 7841

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.

Upvotes: 5

Related Questions