Swift - Operator Function in closure

Introduction

In the previous section you saw that the closure for the sorted() function was reduced to the following:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]
print(sorted(fruits, { $0<$1 } ))

The lesser than < operator is actually a function that works with two operands of type String.

You can simply specify the < operator in place of the closure, and the compiler will automatically infer that you want to use the particular implementation of the < operator.

The preceding statement can be reduced to the following:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]
print(sorted(fruits, { $0<$1 } ))
print(sorted(fruits, < ))

To sort the array in descending order, simply use the greater than > operator:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]
print(sorted(fruits, { $0<$1 } ))
print(sorted(fruits, >))

Related Topic