Kiel Gillard
Kiel Gillard

Reputation: 193

How to compile Swift code targeting the latest SDKs using Xcode 7 and 8?

The nullability of some methods on the NSURL API changed between iOS 9 and 10.

For example, iOS 10 returns an optional for the URLByAppendingPathComponent function but iOS 9 does not. Using #available isn't going to work because it is not a compile time check.

    let appSupportURL = try! NSFileManager.defaultManager().URLForDirectory(.ApplicationSupportDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    let folder: NSURL
    if #available(iOS 10.0, *) {
        folder = appSupportURL.URLByAppendingPathComponent("Folder", isDirectory: true)!
    } else {
        folder = appSupportURL.URLByAppendingPathComponent("Folder", isDirectory: true)
    }

How can I build the Swift code in my app with both Xcode 7 or Xcode 8 while still targeting the latest iOS SDKs?

Upvotes: 2

Views: 159

Answers (1)

Kiel Gillard
Kiel Gillard

Reputation: 193

At WWDC 2016, Ewa Matejska presented the following technique:

#if swift(>=2.3)
// code that builds against iOS 10 SDK.
#else
// code that builds against iOS 9 SDK.
#endif

This technique is also documented on the Swift blog.

Upvotes: 1

Related Questions