As we have checked in our previous blog, we learned about some higher-order functions in Swift.
In this blog, we are going to explore more Higher-Order functions in Swift.
If you have not read our previous blog, please check that blog as well from here.
Let’s start:
forEach
forEach will iterate through all elements in an array. And unlike for in you can’t use a break and continue statement to exit from the closure for forEach.
Example:
1 2 3 |
let numbers = [1, 3, 8, 5, 6] numbers.forEach { print("\($0)", terminator: " ") } |
Output: 1 3 8 5 6
Map
As in our previous blog we have already learned about maps, in this blog we will understand the types of maps, i.e. compactMap and flatMap
compactMap
The compactMap(_:) will iterate through all elements in an array and will remove nil values from the input array. It’s basically used when we are working with optional.
Example:
1 2 3 4 |
let numbers = [1, 3, nil, 5, 6] let integers = numbers.compactMap { $0 } print(integers) |
Output: [1, 3, 5, 6]
flatMap
flatMap converts a 2D array to a one-dimensional array.
Example:
1 2 3 4 |
let numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let result = numbers.flatMap({ $0 }) print(result) |
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
sort(by:)
sort(by:) will sort all elements according to the condition written inside the body of the closure in the same array.
Example:
1 2 3 4 |
var numbers = [1, 3, 8, 5, 6] numbers.sort { $0 > $1 } print(numbers) |
Output: [8, 6, 5, 3, 1]
sorted(by:)
sorted(by:) will sort all elements according to the condition written inside the body of the closure and return a new array.
Example:
1 2 3 4 5 6 |
let numbers = [1, 3, 8, 5, 6] let sortedArray = numbers.sorted { $0 > $1 } print("numbers: ", numbers) print("sortedArray: ", sortedArray) |
Output:
numbers: [1, 3, 8, 5, 6]
sortedArray: [8, 6, 5, 3, 1]
For more understanding of higher-order functions please check here.
For more interesting blogs check out here.
Thanks for reading