Luca Davanzo
Luca Davanzo

Reputation: 21528

Swift extension for a specific iOS version

I need to create custom extension for my class that depends on iOS version.

So, for instance:

@available(iOS 10.0, *)
extension Foo {
    func test() {
        print("do something for iOS 10.0 and later")
    }
}

What if I would execute test for version between 9.0 (included) and 10.0 (excluded)?

Upvotes: 7

Views: 3257

Answers (1)

Sivajee Battina
Sivajee Battina

Reputation: 4174

I should appreciate you for asking this question.

@available works similarly to #available in that you specify the iOS release you want to target, and then Xcode handles the rest. For example:

@available(iOS 9, *)
func iOS9Work() {
    // do stuff
}

If your deployment target is iOS 8, you can't call that iOS9Work() method without some availability checking first. You can stack up these checks if you need to, for example:

//You need to perform this check before calling
if #available(iOS 9, *) {
    iOS9Work()
}

@available(iOS 9, *)
func iOS9Work() {
  // do stuff
}

In your case you have to call like this:

 if #available(iOS 10, *) {
        Foo()
    }

For more info: Availability Checking in Swift

Upvotes: 2

Related Questions