Custom Sequence, use `for` index don't change, but `while` is normal. why?

struct BoxedFibonacciSequence: Sequence, IteratorProtocol
{
    typealias Element = Int
    var currentIndex = 0
    
    mutating func next() -> Int? {
        defer { currentIndex += 1 }
        return  loadFibNumber(at: currentIndex)
    }
    
    func makeIterator() -> Self {
        return self
    }
}


func loadFibNumber(at index: Int)  -> Int {
    return fibNumber(at: index)
}


var box = BoxedFibonacciSequence()
for v in box {
    print("for index",box.currentIndex)
    if v < 20 {
    } else {
        break
    }
}

let fib = BoxedFibonacciSequence()
var iter = fib.makeIterator()
while let v = iter.next() {
    print("while index",iter.currentIndex)
    if v < 20 {
    } else {
        break
    }
}

//out put:
//for index 0
//for index 0
//for index 0
//for index 0
//for index 0
//for index 0
//for index 0
//for index 0
//for index 0
//while index 1
//while index 2
//while index 3
//while index 4
//while index 5
//while index 6
//while index 7
//while index 8
//while index 9
Answered by Scott in 761444022

The for loop starts by calling your makeIterator() under the covers and then mutates that iterator, leaving your original box instance unchanged.

The while loop is doing basically the same thing, except the makeIterator() call is explicit. If you changed that loop to print fib.currentIndex instead of iter.currentIndex then you would get the same output as the for loop.

Accepted Answer

The for loop starts by calling your makeIterator() under the covers and then mutates that iterator, leaving your original box instance unchanged.

The while loop is doing basically the same thing, except the makeIterator() call is explicit. If you changed that loop to print fib.currentIndex instead of iter.currentIndex then you would get the same output as the for loop.

Custom Sequence, use `for` index don't change, but `while` is normal. why?
 
 
Q