【问题标题】:#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000 equivalent in Swift#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000 等效于 Swift
【发布时间】:2017-07-01 15:36:36
【问题描述】:

什么是 Swift 语法:

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

【问题讨论】:

    标签: ios swift3 xcode8


    【解决方案1】:

    对于最大操作系统版本,没有直接模拟 #if compile-time 指令,但根据更广泛的目标,您可以利用一些技术:

    1. 在 Swift 中有一个 #if 指令用于语言版本(但不是操作系统版本)。请参阅The Swift Programming Language: Language Reference: Statements 的“条件编译块”部分。例如:

      #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 runtime 检查操作系统版本。请参阅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 仅在某些操作系统版本中可用,您可以使用 @available 指令。有关详细信息,请参阅The Swift Programming Language: Language Reference: 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
      }
      

    【讨论】:

    • 感谢您的明确解释!我用 2. 来处理我的情况。
    【解决方案2】:

    如果您想为相同的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 2018-06-29
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 2011-06-09
      • 2011-11-01
      • 1970-01-01
      相关资源
      最近更新 更多