taylor swift taylor swift - 21 days ago 5
Swift Question

does Swift array.count get evaluated each time in a loop

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
get evaluated each time the loop runs? Is it better to store it in a
let
constant before running the loop like this?

let length = array.count
while i < length {
...
}

Answer

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