In Swift, arrays can be deleted in a Forin loop without crashing. This is a very different place from OC.

Run the following code

Var numbers: Array = [1, 2, 3, 4, 5]for _ in numbers {
    numbers.removeLast()
}
Copy the code

We’ll see that the program doesn’t crash. This is because the forin loop (array, set, or any other collection or sequence) in Swift loops through its iterator, and the above code can be converted to the following code:

var numbers: Array = [1, 2, 3, 4, 5]
var numbersIterator = numbers.makeIterator()
while let num = numbersIterator.next() {number.removelast ()// When numbers are removed, numbersIterator is not affected. }Copy the code

In a Forin loop, they are all iterators (structures) of this type and then loop through the iterator. Operating on them during the loop does not affect the value of the generated iterator.