NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

When should you use a repeat loop?

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Swift’s for and while loops are overwhelmingly the most common ways to create loops, but we also have a third option called repeat that is similar to a while loop except it will always run its loop body at least once.

Now, this difference is so small that you might wonder what the point is – if we always want code to run at least once, why not just put it before the loop body as well as inside the loop body?

The answer is partly something programmers call “DRY”: Don’t Repeat Yourself. We usually prefer to write code once and only once, and consider repeated code to be a sign that something has gone wrong. Some folks take this to an extreme and repeat nothing and that’s usually a bad idea, but here we can definitely avoid repeating ourself with a repeat loop.

To demonstrate this to you, I want to show you how you can shuffle an array of numbers. Swift gives us shuffled(), which is code we can run on an array that creates a copy of the array array, randomizes the order of the copy’s items, and returns it.

Now, if we had an array of numbers, we could shuffle it up like this:

let numbers = [1, 2, 3, 4, 5]
let random = numbers.shuffled()

However, that has a potential problem: shuffling 1, 2, 3, 4, 5 could mean we get back 5, 4, 3, 2, 1, it could mean we get back, 1, 4, 3, 5, 2, or it could mean we get back 1, 2, 3, 4, 5 – the exact same array we passed in. It’s random, after all, and sometimes randomness comes in strange forms.

Now, what if we wanted to make sure our randomized array wasn’t the same as the original? That would mean running the shuffle, check whether the original and shuffled numbers match, and if they do then shuffle again. This could potentially happen many times, because in theory it’s possible for the same sequence to come back repeatedly – although it’s increasingly unlikely.

So, using a while loop we might write this:

let numbers = [1, 2, 3, 4, 5]
var random = numbers.shuffled()

while random == numbers {
    random = numbers.shuffled()

That makes random equal to the shuffled numbers in numbers. It then checks whether the new numbers as the same as the old ones, and if so shuffles them again. As you can see, that means we’ve repeated shuffled() in two places. For simple code this isn’t really an issue, but what if the code you needed to repeat was 5 lines of code? Or 20 lines?

Now look at the same code using repeat:

let numbers = [1, 2, 3, 4, 5]
var random: [Int]

repeat {
    random = numbers.shuffled()
} while random == numbers

That tells Swift that random will be an integer array but doesn’t actually fill it with anything. Inside the loop body we assign to it the shuffled numbers, then check whether we have the same values or not – the code is simpler, with no repetition.

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.9/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.