How #available works in Swift

This article from the Big Nerd Ranch blog goes back to 2016, but it’s a great little rundown by Mark Dalrymple of #available, introduced back in Swift 2.0.

Hi! I’m #available!

Sometimes we just use language features like this and don’t really think about what’s going on under the hood when we use them, or perhaps we have a mental model based on past assumptions. However, Mark does a an excellent job filling in some of the details on this handy feature of Swift, explaining not only what it is but also what it is not.

The article also clarifies Xcode’s Target SDK version and Deployment Target version, which can initially be a point of confusion to many developers on the iOS platform.

Here’s a great summary of the article from the article itself (a TLDR;):

The take-away points: #available is not #if—it is not conditional compilation based on OS platform. Instead, at compile time, #available tells the compiler to temporarily raise the SDK level above your deployment target so that you can safely use newer API. At run time, the code will execute depending on the version of the OS the app is running on.