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. Merge two arrays into a new tuple array
Details
In the following code, we combine zip with map to generate a new array. Note: The number of new sequences generated by the zip function is the minimum of the original sequence.Example Code
1 | let a = [1, 2, 3, 4, 5] |
Since the whole operation will stop after a short sequence ends in the zip process, we can also use one-way intervals here. The running results of the following code are the same as those above.
1 | let b = ["a", "b", "c"] |
2. Creating dictionaries from key value sequences
Details
The following code combines the two arrays into a dictionary.
1 | let names = ["Apple", "Pear"] |
Zip and shorthand + can be used to solve the problem of duplicate keys. For example, the array is converted into a dictionary. The dictionary key is the value of the array element, and the dictionary value is the number of occurrences of the element.
1 | let array = [ "Apple", "Pear", "Pear", "Orange"] |
3. Merge the two arrays into a new array
Details
We know that the flatMap function can also open arrays (two-dimensional arrays, N-dimensional arrays) containing arrays into a new array, but the order of elements in the new array is one after another according to the original array order.With zip, two array elements can be inserted at intervals. The following code compares the two methods.
1 | let a = ["a", "b", "c", "d"] |
4. Other convenient operations
Details
4.1 Generate the corresponding button array according to the String array.
1 | let titles = [ "Button 1" , "Button 2" , "Button 3" ] |
4.2 Set the buttons in the button array to the colors in the corresponding color array
1 | zip(self.buttons, self.colors).forEach { (button, color) in |
Reference
[1] https://blog.csdn.net/mo_xiao_mo/article/details/78424769