Swift iOS Version Checking

While iOS 8 is now officially in the wild, it may take a bit of time to reach the level of user adoption that iOS 7 had accumulated over the past year.  If you plan to target the widest number of users for your app (at least in these early days of the iOS 8 roll-out), it’d probably be wise to include iOS 7 in your target audience.

When accommodating iOS 7 users, you’ll inevitably run into instances where you need to check which iOS version the device is running, so that you can implement a fall-back plan for older versions of iOS.

In Objective-C, I’ve seen this accomplished by using pre-processor directives, or with introspection.  Swift, however, has no pre-processor directives in v1.0, and only objects which conform to the NSObject protocol can utilize the respondsToSelector: method call.  What to do?

As it turns out, Apple has guidance that would actually work for both Objective-C and Swift – It involves simply checking the NSFoundationVersionNumber of the device against one of the pre-defined values defined in NSObjCRuntime.h.

To accomplish this in Swift, you can create a new Swift file (I called mine “iOSVersions.swift”) to hold the following code:

Whenever you need to check which iOS version the device is running, you can simply use the iOS8 / iOS7 constants that you just defined – they’re accessible in other Swift files throughout your project:

With these little snippets, you should be empowered to support iOS 7 while taking advantage of new iOS 8-only features and APIs.  You can also begin to move away from deprecated ways of doing things, while not breaking your app for iOS 7 users, so long as iOS 7 retains a significant slice of the iOS version pie.