Summary of Swift cyclic traversal set method

Respect knowledge, please indicate the source: Swift cycle traversal collection method summary


Summary in 2016, I summed up the OC cycle traversal, the article in this: iOS development of the ergodic set (NSArray, NSDictionary, NSSet) method summary. After a lapse of one year, with the gradual improvement of Swift, the use of Swift to develop their own experience and knowledge accumulated projects, it is time to sum up the Swift cycle traversal.
believes that Swift will give you something different, even a surprise.

Summary of Swift cyclic traversal set method
Swit-for.jpeg

The first way: for-in cycle OC continuation of the C language of the for cycle, in the Swift has been completely transformed, we can no longer use the traditional form of the for cycle

Traversing arrays and dictionaries:

/ / iosArray = let = array ["L", "O", "V", "E", "I", "O", "S" for index 0 in 6 print (iosArray[index]) {...} for index in {print 0..< 6 (iosArray[index]) for element in {iosArray} print (element)} / / iosDict = let traversal DICTIONARY ["1": "one", "2", "two", "3", "three", "4": "four" for (key, value) in iosDict print ("{/ / ((key): value"))} / / key and value separately traversing the dictionary let keys = iosDict.keys for K in keys (k) {print} let values = iosDict.values for V in values (V) {print}

The above traversal array uses 2 ways

1
, the first way is Swift in ordinary for loop syntax, in the index index and traverse range of 0… 6 with the in keyword, it should be noted here that the range of 0… 6: 0&lt = index; &lt = 6; 0..&lt, 6; that is: 0&lt = index; < 6, this is not to pay attention to the form of..6: 0&lt. As long as familiar with the Swift syntax, these are not difficult to understand.
expand the form of 1:0… 6 can also be taken to develop a range of elements in the array, the code is as follows:

Let sectionArray = iosArray[1... 4] print (sectionArray) output: 4 elements - 0: "O": "V" - 1 - 2 - 3: "E": "I"

Expand the form of 2:0… 6 can also be used to initialize the creation of the array, the code is as follows:

Let numbers = Array (1... 7) print (numbers) output: 7 elements - 0: 1 - 1: 2 - 2: 3 - 3: 4 - 4 - 5: 5: 6: 7 - 6

In other words, the scope of the situation involved in the future can try 0… This form, see if you can quickly get the specified range of elements, there are plenty of places available, the small partner of their own nuggets, right now, there are a lot of things, such as the 6.

2,
in a similar way to the rapid traversal of the OC, the index does not need to be able to access directly to the array of elements, but also a good understanding of the second.


The traversal of the dictionary can be divided into simultaneous or separate traversal of key and value

1,
and key and value traversal using the Swift tuples and tuple values of various types can be combined into a composite value, it is very convenient to use, so you can also get the dictionary key and value.

2,
alone key value traversal dictionary, note that keys and values are not Array, and therefore can not be used directly access the keys[0] form, their actual type is LazyMapCollection< [Key: Value], Key>, is clearly not a group number. Of course we can convert them into arrays, as follows:

The dictionary / / Kyes into an array of let keys = Array (iosDict.keys) print (keys[0])

Since the dictionary is out of order, all this does not mean much.

Second ways: Swift for loop brings surprises will be singled out as following second ways is not appropriate, in fact, this part still belongs to Swift for-in, a separate out of the way of love, let us look at the time more eye-catching.

reverse traversal

For index in / / reverse traversal of the array (0... 6).Reversed (print) {(iosArray[index])} for element in iosArray.reversed (print) {(element)} / / reverse traversal dictionary for (key, value) in (iosDict.reversed) {print ("/ /: (key) (value)")}

1,
above, whether it is 0. 6 of this index or fast traversal, can be directly called reversed () function to achieve the reverse traversal.

2,
for the reverse traversal of the dictionary, some small partners may have some questions, the dictionary is unordered, backward and forward traversal there is a difference, it seems meaningless. There is a need to explain, the dictionary is said not to guarantee the order disorder, but in memory is in order, but this order is not necessarily in accordance with our deposit or encoding order, so the reverse traversal dictionary is meaningful.

3,
saw OC last year I loop through the summary of the buddy will remember, when we need to change the elements of the set to traverse the collection when the forward traversal will appear occasionally crash problem, especially the large amount of data when almost every time will crash, when we use the reverse traversal without a crash problem in Swift, in order to ensure the stability of the program, also suggested in traversing a collection need to modify the collection elements by reverse traversal.

Development: reversed () function is set to return to give us an order upside down, then we can use this function to get a set of reverse order is very convenient, the code is as follows:

Gets an array of let reversedArray / / reverse = Array (iosArray.reversed) (print) (reversedArray)

ForEach traversal

If there is a small partner that for-in traversal cumbersome, Swift also provides a more simple traversal of forEach, the code is as follows:

The use of forEach traversal iosArray.forEach {/ / positive (word) in print (word)} / / forEach (.ForEach) iosArray.reversed reverse traversal {(word) in print (word)}

Note: 1, can not use “break” or “continue” to exit the traversal; 2, use “return” to end the current loop through this way, only the end of the loop through the current closure, and not to skip the subsequent code call.


Stride traversal

Stride traversal is divided into
: Strideable> stride< T (from start: T, to end: T, by stride: T.Stride
) and
stride< T: Strideable> (from start: T, through end: T, by stride: T.Stride)
two traversal code, as follows:

//stride for index in stride forward traversal (from: 1, to: 6, by: 1) {print (index) print (iosArray[index]) //stride for index} in stride jump forward traversal (from: 0, to: 6, by: 2) {print (index) print (iosArray[index]) //stride for index} reverse traversal in (stride from: 6, to: 1, by: -1) {print (index) print (iosArray[index]) //stride through for index} forward traversal in stride (from: 0, through: 6, by: 1) {print (index) print (iosArray[index])}

1,
stride as the meaning of the word “stride”, using the way of traversal of the benefits of natural can be flexible according to their own needs such as ergodicity, we sometimes need to traverse the index even or base elements, or every 3 elements a traversal and similar requirements can be easily achieved;

2,
stride traversal can also achieve a forward and backward traversal, in the back of the by to increase the positive increase in the number of positive traversal, add a negative number of diminishing backward traversal;

3,
to and through two traversal difference is that to does not contain behind the index, and the through contains behind the index, with to: 6 and through: 6 cases, to:< 6 or > 6, through:< =6 or > =6, as is < or > depends on forward traversal or reverse traversal.

The third way: block based traversal OC has a very elegant based on fast traversal, Swift maintained the excellent interface, the following to see how Swift is used.

forward traversal

/ / for (n, C = array iosArray.enumerated (in)) {print ("/ /: (n) (c)")} / / for (n, C traversal Dictionary) in (iosDict.enumerated) {print ("/ /: (n) (c)")}

Note: 1, (n, c) n c said the input sequence of elements, each element in the collection; 2, the array is ordered, so in the array n can also denote each element in the array index, and the dictionary is in disorder, but will still be in accordance with N 0, 1, 2… The sequential input, thus could not be represented in the dictionary index.


reverse traversal

/ / reverse traversing arrays (n, c) for (iosArray.enumerated).Reversed (in) {print ("/ /: (n) (c)")} / / reverse traversal dictionary for (n, c) in (iosDict.enumerated) (.Reversed) {print ("/ /: (n) (C)"})

Reverse traversal is directly in the enumerated () function call reversed () function.

Summary on the summary of OC traverse, the author advocated looping through block based traversal as compared to the other, based on circular block is set to traverse the elegance and practicality of the creature, but in Swift some changes happened.

1,
listed above 3 traversal, in fact, this classification is not rigorous, they just show the form is not the same, are essentially for-in loop variants, are based on the enumeration of cyclic traversal, so we do not have too seriously their essential difference, in the form of region can be separated. Do not affect our use;

2,
in OC in addition to a few situations we need to use for (int i = 0; I < n; i++) approach, we recommend the use of fast traversal based on enumeration. In Swift instead of for (int i = 0; I < n; i++) in the form of for index in gives us 0… 6, this is not just the syntax changes, essentially has been completely different, more convenient to use, but also has more convenient interface function. And compared to other traversal method also has a lot of advantages, so in Swift we can not choose one way, should choose the appropriate method according to the situation.

In 3,
in OC based on the ergodic block there is a concurrent traversal, I did not find the corresponding method in Swift, see the thousands of lines of code is not found, please inform also find buddy, indebted forever. Of course, the use of concurrency is not much, we often want to set the elements of the sequence, there is no difference in time and efficiency.

The tail put aside our habit of using Swift in a lot of time than the OC or other programming language more concise and practical, although many still rely on the OC Swift programming, and dynamic Swift this compile time language is still running on OC, and UIKit similar to a number of libraries are also based on OC. Swift set of other languages in a single character and personality, from the for cycle and a series of small changes can be seen in its unique place. Completely replace OC need time, but at this time to join the Swift is the best time, what are you waiting for?