Thursday, June 7, 2018

Swift 4.2

Ole Begemann:

I made a “What’s new in Swift 4.2” playground for Xcode 10: new collection algorithms, random numbers, enumerating enum cases, and more.

Ole Begemann:

Working with random numbers in Swift used to be a bit of pain because there was no native random number API. Developers had to fall back on C APIs provided by the operating system, which are often easy to misuse. Moreover, the preferred random number API differs between platforms (e.g. arc4random vs. rand vs. random), making it difficult to write cross-platform code.

Swift 4.2 makes this much easier by including a native and fairly full-featured random number API in the standard library. You can read about the full API and its design rationale in Swift Evolution proposal SE-0202).

Previously: Swift 4.1.

Update (2018-06-09): Roadfire Software (via Hacker News):

In What’s New in Swift at WWDC 2018, Apple gave a quick overview of what’s new in Swift 4.2 and Swift 5. You can read my notes below, or you can watch the 40-minute video and download the slides from Apple.

Ole Begemann:

Problem: a manual CaseIterable implementation risks becoming incorrect as a type evolves. The compiler doesn’t catch this.

Solution: a dummy function whose only purpose is to produce a compile error on (almost) the correct line when a new case is added.

It’s ugly but it works.

Update (2018-06-12): Ole Begemann:

New in Swift 4.2, the compiler can generate a collection of an enum’s cases, relieving you from the error-prone task of maintaining such a list yourself. The Swift Evolution proposal that introduced this feature is SE-0194.

[…]

The manual implementation is easy enough to write, but it has a major downside compared to compiler-generated code: we now have to remember to keep it up to date. If we later add another workout type to our enum, the compiler won’t alert us that our allCases implementation is no longer correct. It will just silently return the wrong result.

The only workaround I can think of is a little ugly, but it solves this problem in a really interesting way.

Update (2018-08-14): Mattt Thompson:

Swift 4.2 refines Hashable even further by introducing the Hasher type and adopting a new universal hashing function.

Update (2018-09-03): Brent Simmons:

The point still stands, though, that automatic hashing in the case of objects with lots of properties might be a performance hit. As always — use the profiler.

2 Comments RSS · Twitter

Leave a Comment