Translator: I laugh a little; Proofreading: PMST; Finalized: shanks
In the first article in this series, you learned how to avoid forced unpacking of optional types and save “ponies” 🐴. In Part 2, we’ll simplify the previous code to make it look swift-er (Swift programming language style) and introduce you to the map() and flatMap() methods.
In today’s article we will discuss the map() and flatMap() methods of arrays.
Antecedents feed1
Note: The following is the code left above:
|
The goal of this article is to use more “swift-style” patterns and syntax to make the code look better and cleaner.
Map () method introduction
Map () is a method provided by Array that takes a function as an argument and performs a function transformation on each element of the Array to get a new value. This transforms the array [X] to the new array [Y] without creating a temporary mutable array (note: the items variable in the code above), simply by providing a mapping of X->Y.
In this case, instead of looping for as before, we use the map() method on jsonItems(JSON data: stored in an array of type dictionary), passing in a transformation function (closure), Convert each NSDictionary-type array element to the ListItem instance we want:
|
This may seem like a small change, but it lets us focus on how to convert NSDictionary to ListItem, which is the heart of the problem, after all. More importantly, it avoids creating a new intermediate array, as it did in ObjC. We should avoid this as much as possible.
Wrong data
There is one problem with the current code: even though the input data is not available, we still create a ListItem instance (and return it added to the resulting array jsonItems). So, if some NSDictionary is invalid, the final output array is filled with empty instances of ListItem() that make no sense. What’s more, we are still killing some ponies 🐴. When we use NSURL! The code allows us to create instances of ListItem() without NSURL (we don’t have a valid URL key value, so accessing item.url doesn’t work) when we access an invalid NSURL! , the program will crash.
To solve this problem, we modify the transform function slightly so that it is more appropriate to return ListItem with a nil value when the input value is invalid than to return ListItem with an error or no content.
|
But if the function parameter type passed in jsonitems. map is NSDictionary -> ListItem? , we end up with a [ListItem? Arrays, the places that were not available with NSDictionary are replaced by nil. Better than before, but not enough.
Use flatMap ()
This is where flatMap() comes to the rescue.
FlatMap () is similar to map(), but flatMap() uses T->U? Conversion instead of T->U, and if the converted array element is nil2, it is not added to the final array.
Syntactically, you can think of a flatMap as simply processing an array with a map and then “flattening” (as the name implies) the resulting array, which means stripping elements of nil from the output array.
The example code rewritten by the flatMap method is as follows:
|
Now we just return valid ListItem objects where all keys are 3 (NSURL is not nil guaranteed). Otherwise, a GUARD statement is executed and a nil value is returned telling flatMap not to add these invalid elements to the returned result array.
It’s better and safer that way, right? We solved the data exception problem and prevented invalid ListItem entries from being added to the array when there was an error input.
conclusion
We still have a lot of work to do, but let’s do that for today (let’s prepare material for the next article in this series!).
In this article, we learned how to replace the for loop with a map or flatMap to ensure that the output array will work even if the input data is not available. That’s a lot of progress.
In the next article, YOU’ll see how overriding the ListItem class with structs can help you explore other uses of map and flatmaps-especially when dealing with Optionals.
In the meantime, I encourage you to take the time to dig deeper into the use of map() and flatMap() on arrays. I know they may seem complicated to you the first time, but once you learn them, you’ll want to use them all the time.
1: Please imagine some words for a show
2: flatMap also does something else. For example, transform a two-dimensional array into a one-dimensional array, for example, [[T]] -> [T]. But here, we just need to focus on how to use T->U? The transformation of [T] transforms into [U].
3: Notice that in our code, NSDictionary is allowed to have no icon key, which means we think a ListItem can have no icon at all. But the other keys are required.
This article is translated by SwiftGG translation team and has been authorized to be translated by the authors. Please visit swift.gg for the latest articles.