taylor swift - 10 months ago 41

Swift Question

I suppose this is a question that must get asked for every language, but when you write for example:

`while i < array.count {`

...

}

does

`array.count`

`let`

`let length = array.count`

while i < length {

...

}

Answer Source

`while`

loops (and `do while`

loops) have their predicates evaluated on each iteration.

`for`

loops evaluate the sequences once.

Here's is a demonstration:

```
var array: [Int]
print("Test Case 1 - while i < array.count")
array = [1, 2, 3, 4, 5, 6]
var i = 0
while i < array.count {
print(array[i])
if i < 3 { array.append(123) }
i += 1
}
print("\r\nTest Case 2 - for i in array.indices")
array = [1, 2, 3, 4, 5, 6]
for i in array.indices {
print(array[i])
if i < 3 { array.append(123) }
}
print("\r\nTest Case 3 - for i in 0 ..< array.count")
array = [1, 2, 3, 4, 5, 6]
for i in 0 ..< array.count {
print(array[i])
if i < 3 { array.append(123) }
}
```

Test Case 1 - while i < array.count

1

2

3

4

5

6

123

123

123

Test Case 2 - for i in array.indices

1

2

3

4

5

6

Test Case 3 - for i in 0 ..< array.count

1

2

3

4

5

6