It will take about 3 minutes to finish reading this article.
This zip function is not used to compress files. It is used to merge the elements of two sequences one by one to generate a new sequence.
1. map
Map is a common higher-order function that maps each element in a collection to another collection and then returns a new collection.
1 |
|
In this example, we multiply each element in the original array by 2 and store the result in a new array.
We can customize its custom implementation and write it into the Array extension:
1 | func customMap<T>(_ tansform:(Element)->T) -> [T] { |
The call is as follows:
1 | let a = [1, 2, 3, 4, 5] |
2. reduce
reduce is another common higher-order function that combines all elements in a collection into a single value. Its usage is as follows:
1 | let a = [1, 2, 3, 4, 5] |
In this example, we add all the elements in the original array and store the result in a variable.
The custom implementation is as follows:
1 |
|
The call is as follows:
1 | let a = [1, 2, 3, 4, 5] |
3. filter
Filter is a common high-order function that can filter out elements that meet conditions from a set and then return a new set. Its usage is as follows:
1 | let a = [1, 2, 3, 4, 5] |
In this example, we filter out all even elements in the original array and store the results in a new array.
The custom implementation is as follows:
1 | func customFilter(_ isInclude:(Element) -> Bool) ->[Element] { |
The call is as follows:
1 | let a = [1, 2, 3, 4, 5] |
4. flatMap
flatMap is a common higher-order function that flattens a nested collection into a single collection. Its usage is as follows:
1 | let a = [[1, 2], [3, 4], [5, 6]] |
In this example, we flatten an array of three arrays into a single array and store the result in a new array.
Its custom implementation is as follows:
1 | func customFlatMap<T>(_ transform: (Element) -> [T]) -> [T] { |
1 | let a = ["a", "b", "c", "d"] |