Monday, October 11, 2021

Simplifying Backwards Compatibility in Swift

Dave DeLong:

Every year as new OS and Swift versions are released, the question comes up over and over again: “how do I use this new thing while also supporting older versions?”. While we have a bunch of “availability” tools at our disposal (and I’ll be using them in this post), they always come across as somewhat cumbersome: we need to do inline checks, or we have conditional logic flow that obfuscates the intent of some of our code, and so on.

[…]

At first glance, this doesn’t look very useful; it’s a struct that holds a single value, and it doesn’t do anything. This is by design. Backport exists to serve as a holding space (namespace) for shims: the conditional code we must write in order to do proper availability checking.

[…]

Unfortunately, I have not come up with a good way to backport things like specific properties on SwiftUI’s EnvironmentValues, such as .headerProminence.

I have typically done this sort of thing by declaring prefixed category methods, but this technique lets you keep the original method name by adding a namespace.

Previously:

Update (2021-10-19): Christian Tietze:

Behold: @davedelong’s Backport, but for cross platform SwiftUI

Update (2021-11-23): Jesse Squires:

If you are working on a multiplatform SwiftUI project, you will start accumulating #if os() checks and #if canImport() checks. Overtime, these start to accumulate and — in addition to being unsightly — they make your code much more difficult to read. When possible, I have started to encapsulate these preprocessor directives to improve code organization and readability.

Comments RSS · Twitter

Leave a Comment