Swift - Function Using Closures

Introduction

Closures are self-contained blocks of code.

It can be passed to functions to be executed as independent code units.

A closure is like a function without a name.

Closure is Swift's way to create Lambda expressions.

Suppose you have the following array of integers:

let numbers =  [5,2,8,7,9,4,3,1]

To sort this array in ascending order, use sorted() function. It accepts two parameters:

  • An array to be sorted
  • A closure that takes two arguments of the same type as the array, and returns a true if the first value should appear before the second value

In Swift, functions are special types of closures.

The following ascending() function takes two arguments of type Int and returns a Bool value.

func ascending(num1:Int, num2:Int) -> Bool {
    return num1<num2
}

If num1 is less than num2 , it returns true.

You can now pass this function to the sorted() function, as shown here:

var sortedNumbers = sorted(numbers, ascending )

The sorted() function will now return the array that is sorted in ascending order.

You can verify this by outputting the values in the array:

let numbers =  [5,2,8,7,9,4,3,1]

print("Unsorted")
print(numbers)
func ascending(num1:Int, num2:Int) -> Bool {
    return num1<num2
}

var sortedNumbers = sorted(numbers, ascending )
print("Sorted")
print(sortedNumbers)

The sorted() function does not modify the original array.

It returns the sorted array as a new array.

Related Topic