原文連結:http://nshipster.com/swift-system-version-checking/
前言
C VS Swift
- C不安全 (這裡主要指指標的使用)
- C中有未定義的行為 (只宣告,不初始化)
- C中的前處理器解釋功能缺陷
OC中的API檢查主要是通過C預處理根據當前classs傳送respondsToSelector:
和 instancesRespondToSelector:
來達成的:
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
if ([NSURLSession class] &&
[NSURLSessionConfiguration respondsToSelector:@selector(backgroundSessionConfigurationWithIdentifier:)]) {
// ...
}
#endif
Swift根據特定系統以及指令集架構對編譯器做了完全的限制。
#if DEBUG
println("OTHER_SWIFT_FLAGS = -D DEBUG")
#endif
Function Valid Arguments
os() OSX, iOS
arch() x86_64, arm, arm64, i386
#if os(iOS)
var image: UIImage?
#elseif os(OSX)
var image: NSImage?
#endif
不幸的是,os()
沒有提供OS X與iOS特定的版本號,這也意味著我們只能在執行時進行檢查。
NSProcessInfo
為了讓Swift增加執行時API版本判斷的介面友好性,iOS8在NSProcessInfo
類增加了operatingSystemVersion
屬性以及isOperatingSystemAtLeastVersion
方法。
isOperatingSystemAtLeastVersion
為了檢驗APP是不是在iOS8上跑,isOperatingSystemAtLeastVersion
方法是最直接的方法:
if NSProcessInfo().isOperatingSystemAtLeastVersion(NSOperatingSystemVersion(majorVersion: 8, minorVersion: 0, patchVersion: 0)) {
println("iOS >= 8.0.0")
}
operatingSystemVersion
若想做版本對比,可以直接校驗operatingSystemVersion
屬性,配上Swift中的switch
語句。
let os = NSProcessInfo().operatingSystemVersion
switch (os.majorVersion, os.minorVersion, os.patchVersion) {
case (8, _, _):
println("iOS >= 8.0.0")
case (7, 0, _):
println("iOS >= 7.0.0, < 7.1.0")
case (7, _, _):
println("iOS >= 7.1.0, < 8.0.0")
default:
println("iOS < 7.0.0")
}
注意:使用
NSStringCompareOptions.NumericSearch
進行版本字串數值比較的時候,舉個例子:
“2.5” < “2.10”。
使用NSComparisonResult
效果也是一樣的。
NSAppKitVersionNumber
另外一個確認API是否可用的方式是去校驗框架版本號。不幸的是,Foundation
中NSFoundationVersionNumber
與Core Foundation
中kCFCoreFoundationVersionNumber
已經彌久未更了。
但是在OS X
的APPKit
中的NSAppKitVersionNumber
我們還是能夠獲取我們想要的資訊:
if rint(NSAppKitVersionNumber) > NSAppKitVersionNumber10_9 {
println("OS X >= 10.10")
}
使用
rint
先四捨五入版本號後再與NSAppKitVersionNumber
做比較。
總結
Swift中系統版本號校驗須知:
- 使用
#if os(iOS)
前處理器來判斷目標物件是iOS (UIKit)
亦或是OS X (AppKit)
。 - 最小配置物件如果是8.0以上,使用
NSProcessInfo operatingSystemVersion
或者isOperatingSystemAtLeastVersion
。 - 如果配置物件是7.1以下,在
UIDevice systemVersion
使用compare
中的NSStringCompareOptions.NumericSearch
進行版本確認。 - 如果是OS X上的部署,可以使用
AppKit
中的NSAppKitVersionNumber
常量進行對比。