#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000 相当于 Swift

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000 equivalent in Swift

Swift 语法是什么:

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
//...
#endif

最大 OS 版本的 #if 编译时指令没有直接模拟,但根据更广泛的 objective,您可以利用一些技巧:

  1. Swift 中有一个针对语言版本的 #if 指令(但不是 OS 版本)。请参阅 The Swift Programming Language: Language Reference: Statements 的 "Conditional Compilation Block" 部分。例如:

    #if swift(>=3.0)
    func foo(with array: [Any]) {
        print("Swift 3 implementation")
    }
    #else
    func foo(with array: [AnyObject]) {
        print("Swift 2 implementation")
    }
    #endif
    
  2. 您可以执行 #available 运行时 检查 OS 版本。请参阅 The Swift Programming Language: Control Flow 的“检查 API 可用性部分”。例如,UserNotifications 框架在 iOS 10 可用,因此您可以执行以下操作:

    private func registerForLocalNotifications() {
        if #available(iOS 10, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in
                guard granted && error == nil else {
                    // display error
                    print(error?.localizedDescription ?? "Unknown error")
                    return
                }
            }
        } else {
            let types: UIUserNotificationType = [.badge, .sound, .alert]
            let settings = UIUserNotificationSettings(types: types, categories: nil)
            UIApplication.shared.registerUserNotificationSettings(settings)
        }
    }
    
  3. 如果您的 API 仅在某些 OS 版本中可用,您可以使用 @available 指令。有关详细信息,请参阅 The Swift Programming Language: Language Reference: Attributes 中的 "Declaration Attributes" 讨论。例如:

    @available(iOS, introduced: 9.0, deprecated: 11.0)
    func someMethod() {
        // this is only supported iOS 9 and 10
    }
    

    或者,

    @available(iOS 10.0, *)
    func someMethod() {
        // this is only available in iOS 10 and later
    }
    

如果你想对相同的 swift 版本进行条件编译,你可以使用 ex.

let session = ASWebAuthenticationSession(url: URL(string: "https://my.com")!, callbackURLScheme: "") { (url, error) in }
#if compiler(>=5.1)
if #available(iOS 13.0, *) {
    session.presentationContextProvider = self
}
#endif

编译版本见swift --version