UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

When should you use a repeat loop?

Paul Hudson    @twostraws   

Updated for Xcode 15

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 RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

BUY OUR BOOKS
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.