如何使用 Xcode 7 和 8 编译针对最新 SDK 的 Swift 代码?

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

NSURL API 上某些方法的可空性在 iOS 9 和 10 之间发生了变化。

例如,iOS 10 returns an optional for the URLByAppendingPathComponent function but iOS 9 does not。使用 #available 不会起作用,因为它不是编译时检查。

    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)
    }

如何使用 Xcode 7 或 Xcode 8 在我的应用程序中构建 Swift 代码,同时仍以最新的 iOS SDK 为目标?

在 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

这个技巧也是documented on the Swift blog