Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
When should you use a repeat loop? - a free tutorial

NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

When should you use a repeat loop?

Paul Hudson    @twostraws   

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 Instabug

SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.

Start your free trial!

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

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Link copied to your pasteboard.