Updating to Swift 4.2

Swift 4.2 is a major release and shipped with Xcode 10. It comes with a lot of code improvements for which the best way to start is to watch the WWDC 2018: What’s New in Swift session. Some of the improvements are easy to implement in your existing code.

Replace strongSelf with self

SE-0079 makes it possible to upgrade self from a weak to a strong reference by allowing the use of optional binding. If you have a lot of unwraps like this:

guard let strongSelf = self else { return }

Then you can go for a find an replace to replace strongSelf with self.

Replacing // TODO: with the new #warning

You might have added a custom run script to show warnings for // TODO: like explained in several blog posts. Just like before in Objective-C, we can now replace those by simple #warning statements pointing out that we need to update that piece of code.

Iterating over all cases of an enum

Before Swift 4.2 it was hard to get all cases of an enum. Several solutions made it possible from which you might have implemented one of these in your project.

SE-0194 introduces a new CaseIterable protocol to derive a Collection of all Enum Cases with a new static var allCases.

enum CompassDirection: CaseIterable {
    case north, south, east, west

print("There are \(CompassDirection.allCases.count) directions.")

Generating random values

arc4random_uniform is common and was used before Swift 4.2 to generate random values. With SE-0202 Random Unification it’s now a lot easier to generate a random integer:

Int.random(in: 1..<5)

a random boolean:


a shuffled array:

let shuffledNumbers = [0, 1, 2, 3, 4].shuffled()

or to get a random element:

let bingoNumbers = [0, 1, 2, 3, 4, 5]

If your project uses randomness anywhere you might want to check whether these newly introduced methods can improve your existing code.

More changes in Swift 4.2

The above examples are just a piece of all the introduced changes. Ted Kremenek gives us a detailed overview of all the changes in his blog post Swift 4.2 Released!.

Apple’s guide in migrating

Apple makes it easy for you to migrate, especially when migrating from an older Swift version. Check out Migrating to Swift 4.2 or use the built-in migration tool which you can find under Edit -> Convert -> To Current Swift Syntax.

Getting more out of Xcode 10

If you like to get the most out of Xcode 10, check out Enabling newly added opt-in features in Xcode 10 and Build performance analysing in Xcode 10