WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

Key points

There are three Swift features that are so important – and so commonly used – that they are worth revising to make sure you’re comfortable with them.

The first piece of code I’d like to look at is this one:

for (index, line) in lines.enumerated() {
    let parts = line.components(separatedBy: ": ")

This might seem like a new way of writing a loop, but really it’s just a variation of the basic for loop. A regular for loop returns one value at a time from an array for you to work with, but this time we’re calling the enumerated() method on the array, which causes it to return two things for each item in the array: the item’s position in the array, as well as the item itself.

It’s common to see enumerated() in a loop, because its behavior of delivering both the item and its position is so useful. For example, we could use it to print out the results of a race like this:

let results = ["Paul", "Sophie", "Lottie", "Andrew", "John"]

for (place, result) in results.enumerated() {
    print("\(place + 1). \(result)")

Note that I used \(place + 1) to print out each person’s place in the results, because array positions all count from 0.

The second piece of code we’re going to review is this:

var score: Int = 0 {
    didSet {
        scoreLabel.text = "Score: \(score)"

This is a property observer, and it means that whenever the score integer changes the label will be updated to match. There are other ways you could ensure the two remain in sync: we could have written a setScore() method, for example, or we could just have updated the scoreLabel text by hand whenever the score property changed.

The former isn’t a bad idea, but you do need to police yourself to ensure you never set score directly - and that’s harder than you think! The second is a bad idea, however: duplicating code can be problematic, because if you need to change something later you need to remember to update it everywhere it’s been duplicated.

The final piece of code I’d like to look at again is this:

DispatchQueue.global().async { [weak self] in
    // do background work

    DispatchQueue.main.async {
        // do main thread work

That code uses Grand Central Dispatch to perform some work in the background, then perform some more work on the main thread. This is extremely common, and you’ll see this same code appear in many projects as your skills advance.

The first part of the code tells GCD to do the following work on a background thread. This is useful for any work that will take more than a few milliseconds to execute, so that’s anything to do with the internet, for example, but also any time you want to do complex operations such as querying a database or loading files.

The second part of the code runs after your background work has completed, and pushes the remaining work back to the main thread. This is where you present the user with the results of your work: the database results that matched their search, the remote file you fetched, and so on.

It is extremely important that you only ever update your user interface from the main thread – trying to do it from a background thread will cause your app to crash in the best case, or – much worse – cause weird inconsistencies in your app.

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.