Mervyn Ong
Mervyn Ong

Reputation: 225

Is it possible to define a variable for only a specific iOS version in Swift? On the class level

Is it possible to achieve this on the Class level of an object? Specifically looking at this to have an app containing WatchConnectivity but also suppporting iOS8

class Test {
    if #available(iOS 9, *) {
        let session: WCSession ......
    }
}

Upvotes: 4

Views: 4055

Answers (2)

Mehrdad
Mehrdad

Reputation: 1208

You can wrap it with a computed property, for instance for UIMenu:

@available(iOS 13.0, *)
var menu: UIMenu? { // use this as a getter for what you want
   return _menu as? UIMenu
}
var _menu: Any? // use this reference as a setter for what you want

Upvotes: 4

JRG-Developer
JRG-Developer

Reputation: 12663

You can use a computed static property:

public class Example {  
  public static var answerToEverything: Int {
    if #available(iOS 9, *) {
      return 42
    } else {
      return 0
    }
  }
}

Or, you can consider using @available attribute instead:

public class Example {
  @available(iOS, introduced=1.0)
  public static var answerToEverything: Int = 42
}

where 1.0 is the version of your library (not iOS).

This would be useful if you're more concerned about making sure it's used on iOS and less concerned about the iOS version.

Upvotes: 7

Related Questions