Pete On Software

RSS Feed

Swift – Repeat Keyword

RepeatIn the Swift Programming Language – like all programming languages – we are given a lot of ways to control the flow of the program. Back when Swift was first introduced, I wrote a post to talk about the ways that Swift offered to control program flow.

One of the ways that I covered in that post was the while keyword. Using a while statement will cause the program to evaluate a condition first before it would ever execute the block. Take this code for example:

var counter:Int = 0

while counter < 10 {
    print("counter is at \(counter)")
    counter++
}

This results in the output of:

counter is at 0
counter is at 1
counter is at 2
counter is at 3
counter is at 4
counter is at 5
counter is at 6
counter is at 7
counter is at 8
counter is at 9

However, if you ran the following code:

var counter:Int = 0

while counter > 0 {
    print("counter is at \(counter)")
    counter++
}

There is no output. Since counter is 0 and the while block only executes for positive values, nothing happens.

Let's see how repeat is different. We'll try the first example again.

var counter:Int = 0

repeat {
    print("counter is at \(counter)")
    counter++
} while counter < 10

This results in the same output of

counter is at 0
counter is at 1
counter is at 2
counter is at 3
counter is at 4
counter is at 5
counter is at 6
counter is at 7
counter is at 8
counter is at 9

But, the second example of

var counter:Int = 0

repeat {
    print("counter is at \(counter)")
    counter++
} while counter > 0

Results in the code running for ever and ever and ever. It only asked if the variable was greater than 0 after the first pass. Since by the time the code had exited the repeat block the value of counter was 1 (and therefore positive), we just kept going (I stopped it when the last few entries looked like this):

counter is at 10789
counter is at 10790
counter is at 10791
counter is at 10792
counter is at 10793
counter is at 10794
counter is at 10795
counter is at 10796
counter is at 10797
counter is at 10798
counter is at 10799

You might be saying to yourself, but Pete.. this sounds exactly like a do-while loop vs a while loop. Well, you'd be 100% correct. Even according to the Swift documentation, "The repeat-while loop in Swift is analogous to a do-while loop in other languages". C'est la vie!

Leave a Comment