Blog / June 11, 2022 / 2 mins read / By Mahi Garg

$0, $1 … $n in Swift

In order to use any parameter in a closure or a higher-order function, we need to name the parameter inside the closure or higher-order function.

The syntax looks like the below.

let array = [1, 2, 3, 4, 5, 6]
let evenNumbers = array.filter { item in
    item % 2 == 0
}
print(evenNumbers)

This filter function takes a single argument which is another function that is of (Int) -> Bool type. The inner function takes every element of the array one by one and checks if that is an even number or not. It returns true if the condition is true else it returns false.

The parameter passed inside the function can be replaced with $0.

$0 represents the first parameter of closure or higher-order function.

It can be used with both closers or higher-order functions.

The same syntax will look like below.

let array = [1, 2, 3, 4, 5, 6]
let evenNumbers = array.filter {
    $0 % 2 == 0
}
print(evenNumbers)

In case the number of parameters are more than one,

$0, $1 up to $n can be used.

For example, look at the below case where there are two parameters passed to the higher-order function namely index and item.

let array = [1, 2, 3, 4, 5, 6]
let filterArray = array.enumerated().filter {index, item in
    //I am doing some rocket science here
    print("Item at \(index) is \(item)")
    return index != 2 && item % 2 == 0
}
print(filterArray)

We can use $0 for index and $1 for item in the same example.

let array = [1, 2, 3, 4, 5, 6]
let filterArray = array.enumerated().filter {
    //I am doing some rocket science here
    print("Item at \($0) is \($1)")
    return $0 != 2 && $1 % 2 == 0
}
print(filterArray)

These numbers can go up to any number of parameters passed to the inner function.

I’ll personally suggest using named parameters if the parameters are more than three as it’s difficult to remember which $ variable is what. Up to three is really helpful.

Comments