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

时间:2016-06-22 02:19:48

标签: xcode swift foundation

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

例如,URLByAppendingPathComponent功能的iOS 10 returns an optionaliOS 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?

1 个答案:

答案 0 :(得分:1)

在2016年WWDC上,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