A preliminary exploration of advanced functions
In Swift, there are a few higher-order functions:
- map: For each element of a given array, perform a mapping in the closure and place the mapping result in the array to return.
- flatMap: performs a mapping in the closure for each element of a given array, performs a merge operation on the mapping results, and then places the result after the merge operation in the array to return.
- compactMap: For each element of a given array, perform mapping in the closure and place the non-empty mapping results in the array to return.
- compactMap performs mapping in closure for each element of a given array, and places non-empty mapping result-key value pairs in the dictionary to return.
- filter: For each element of a given array, perform operations in the closure and return the elements that meet the conditions in the array.
- reduce: For each element of a given array, perform operations in the closure to merge the elements and return the merge result.
Through the above explanation, we roughly understand what these functions are used for. Let’s take a look at how to use them in the code through a few examples.
map
For map functions, the usage scenario is to map the type of the array to another type. For example, we have a model array, and we take the String type from the server for the id field. In some scenarios, we need to convert it to the Int type, and at this time we can achieve this requirement through the map function.
struct Student { let id: String let name: String let age: Int } let stu1 = Student(id: "1001", name: "stu1", age: 12) let stu2 = Student(id: "1002", name: "stu2", age: 14) let stu3 = Student(id: "1003", name: "stu3", age: 16) let stu4 = Student(id: "1004", name: "stu4", age: 20) let stus = [stu1, stu2, stu3, stu4] let intIds = { (stu) in Int() } print(intIds) //[Optional(1001), Optional(1002), Optional(1003), Optional(1004)]
With the above code, we map the id field from String to the Int? type, which is not the Int type we want. If we need to access elements, we still need to unpack them, then how can we map elements and automatically filter nil's values? At this time, it was compactmap's turn to take action.
compactMap
We replace the above code with:
let intIds = { (stu) in Int() }
At this time, if we print intIds again, we will find that it is already of Int type.
compactMapValues
For Set and Array, you can use compactMap to get non-empty collections, but for Dictionary, this function does not work.
let dict = ["key1": 10, "key2": nil] let result = { $0 } print(result) //[(key: "key1", value: Optional(10)), (key: "key2", value: nil)]
At this time, we need to use the compactMapValues function to obtain a non-empty dictionary.
print(result) //["key1": 10] let result = { $0 } print(result) //["key1": 10]
flatMap
For flatMap, the main application scenario is that you want to obtain an array of single-layer collections. Let’s take a look at the difference between map and flapMap through the following code.
let scoresByName = ["Henk": [0, 5, 8], "John": [2, 5, 8]] let mapped = { $ } // [[2, 5, 8], [0, 5, 8]] print(mapped) let flatMapped = { $ } // [2, 5, 8, 0, 5, 8]
map will place the elements directly in an array, while flatMap will lay the elements flat in an array. In fact, (transform) is equivalent to (transform).joined().
filter
This function is like the meaning of a word: search. Find the elements that meet the criteria and place them in the array to return. For example, we want to find all students older than 18 years old.
let adults = { (stu) -> Bool in >= 18 } print(adults) // Only stu4 students are included in the array
reduce
For reduce, our usage scenario is to perform combination operations on elements in an array, such as we want to calculate how many ages all students are loaded together.
let totalAges = (0) { (result, stu) in return result + } print(totalAges) // 62
The first parameter of the function is the initial value, the first parameter in the subsequent tuple is the result of each calculation, and the second parameter is the element of each traversal. Finally, the calculated result is returned.
Combination use
The biggest advantage of using higher-order functions is that you can perform functional programming. Below we use a few small chestnuts to combine these higher-order functions.
Map String type to Int type and find all students with id greater than 1002
let adults = { (stu) in Int() }.filter { (id) -> Bool in id > 1002 } print(adults) //[1003, 1004]
Calculate the sum of ages for all students with ages older than 12
let totalAge = { (stu) -> Bool in > 12 }.reduce(0) { (result, stu) in return result + } print(totalAge) // 50
Summarize
This is all about this article about Swift advanced functions. For more related content of Swift advanced functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!