Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the higher order functions of Swift

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you what Swift high-order functions are, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

A preliminary study of higher order functions

In Swift, there are the following high-order functions:

Map: performs the mapping in the closure for each element of a given array, and returns the mapping result in the array.

FlatMap: performs the mapping in the closure for each element of a given array, merges the mapping results, and then returns the merged results in the array.

CompactMap: performs the mapping in the closure for each element of a given array, and returns non-empty mapping results in the array.

CompactMap performs the mapping in the closure for each element of a given array, and returns non-empty mapping results-key-value pairs in a dictionary.

Filter: for each element of a given array, the operation in the closure is performed, and the eligible elements are returned in the array.

Reduce: for each element of a given array, perform the actions in the closure to merge the elements and return the merge result.

Through the above explanation, we have a general idea of what these functions are for. Let's take a look at how to use the code through a few examples.

Map

For the map function, the usage scenario is to map the type of the array to another type. For example, we have an array of models, and the id field of the model is of type String from the server. In a certain scenario, we need to convert to type Int, and then we can implement 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 = stus.map {(stu) in Int (stu.id)} print (intIds) / / [Optional (1001), Optional (1002), Optional (1003), Optional (1004)]

With the above code, we map the id field from String to Int? Type, which is not the Int type we want. If we need to unpack elements if we need to access them, how can we both map elements and automatically filter the value of nil? At this point, it was compactmap's turn.

CompactMap

Let's replace the above code with:

Let intIds = stus.compactMap {(stu) in Int (stu.id)}

At this point, we print intIds again and we will find that it is already of type Int.

CompactMapValues

For Set and Array, you can use compactMap to get non-empty collections, but for Dictionary, this function doesn't work.

Let dict = ["key1": 10, "key2": nil] let result = dict.compactMap {$0} print (result) / / [(key: "key1", value: Optional (10)), (key: "key2", value: nil)]

At this point, we need to use the compactMapValues function to get a non-empty dictionary.

Print (result) / / ["key1": 10] let result = dict.compactMapValues {$0} print (result) / / ["key1": 10] flatMap

For flatMap, the main application scenario is that you want to get an array of single-layer collections. 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 = scoresByName.map {$0.value} / / [[2,5,8], [0,5,8]] print (mapped) let flatMapped = scoresByName.flatMap {$0.value} / / [2,5,8,0,5,8]

Map puts elements directly in an array, while flatMap tiles elements in an array. In fact, s.flatMap (transform) is equivalent to s.map (transform). Joined ().

Filter

This function is just like the meaning of the word: find. Find the elements that meet the criteria and return them in an array. For example, we want to find all the students over the age of 18.

Let adults = stus.filter {(stu)-> Bool in stu.age > = 18} print (adults) / / the array contains only stu4 student reduce

For reduce, our use scenario is to combine the elements in the array, for example, we want to calculate how much all the students' ages are loaded together.

Let totalAges = stus.reduce (0) {(result, stu) in return result + stu.age} 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 result of the calculation is returned.

Combined use

The biggest advantage of using higher-order functions is that you can do functional programming. Next, we use a few small chestnuts to combine these high-order functions.

Map String types to Int types and find all students whose id is greater than 1002

Let adults = stus.compactMap {(stu) in Int (stu.id)}. Filter {(id)-> Bool in id > 1002} print (adults) / / [1003, 1004]

Calculate the total age of all students over 12

Let totalAge = stus.filter {(stu)-> Bool in stu.age > 12}. Reduce (0) {(result, stu) in return result + stu.age} print (totalAge) / / 50 is all the content of the article "what are the higher order functions of Swift". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report