BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Swift 4.2 Hits the Road

Swift 4.2 Hits the Road

This item in japanese

One year after the release of Swift 4, Swift 4.2 is now official. It brings a number of improvements to the language and the standard library, including better generics, Hashable protocol, and random number generation. Additionally, writes Swift maintainer Ted Kremenek, Swift 4 delivers faster compile times and improves the debugging experience.

At the language level, Swift 4.2 brings to completion the work started in 4.1 to implement conditional conformance to generics, which enables the specification of conditions that must be satisfied for a type to conform to a protocol. For example:

extension Array: Equatable where Element: Equatable {
  static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool { ... }
}

What Swift 4.2 adds is the possibility of querying a type for conditional conformance at runtime, which crashed when using Swift 4.1, e.g.:


if let array = items as? Equatable { //– safely use == here }

Another useful feature in Swift 4.2 is derived collection of Enum cases, which enables iterating on all cases of an Enum that conforms to the CaseIterable protocol using the .allCases property.

Other improvements to the language include a new API for random number generation and shuffling, better hashing, and type-safe dynamic member lookup.

On the debugging front, Swift compiler now supports #warning and #error directives to flag issues in code. For example:

#warning("Unsafe operation")
#error("Prodive your credentials here")

Kremenek also highlighted improved compiler performance thanks to batch mode compilation and improved runtime performance thanks to a change in calling convention for retain/release cycle.

On a different note, iOS developer Javier Soto tweeted:

A year later, and Swift 4.2 shipped with a ship-stopper KVO bug still unresolved. Don’t use the Swift KVO syntax in an iOS app unless you want random crashes.

Specifically, the bug may be triggered when the KVO keyPathsForValuesAffectingValue method is run on a background thread while the main thread is attempting to register an observer, e.g. to update an UI element.

For all affected developers, PMKVObserver provides a safe, strongly-typed alternative to Swift 4 KVO syntax.

Swift 4.2 is source-compatible with Swift 4 and 3 and is included in Xcode 10. Migration from previous versions is eased through the Swift Migrator tool.

You can get a full overview of what’s new in Swift 4 in the 40-minute presentation Apple gave at WWDC 2018 and more details in the official announcement. A great resource to start learning the new features in Swift 4.2 is Ole Begemann’s Swift 4.2 playground.

Rate this Article

Adoption
Style

BT