Search code examples
iosswift3xcode8

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000 equivalent in Swift


What is the Swift syntax for:

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

Solution

  • There's no direct analog of the #if compile-time directive for max OS version, but depending upon the broader objective, there are a few techniques you can avail yourself of:

    1. There is a #if directive in Swift for language version (but not OS versions). See "Conditional Compilation Block" section of The Swift Programming Language: Language Reference: Statements. For example:

      #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. You can perform #available runtime check for OS versions. See "Checking API Availability section of The Swift Programming Language: Control Flow. For example, UserNotifications framework is available effective iOS 10, so you'd do something like:

      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. If you have an API that is only available in certain OS versions, you can use @available directive. See "Declaration Attributes" discussion in The Swift Programming Language: Language Reference: Attributes for more information. For example:

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

      or,

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