Christina Tsangouri
Christina Tsangouri

Reputation: 187

How do I do availability checking right before declaring a global variable in iOS?

I need to check for availability of iOS 10 in my app before declaring the center variable.

This is my App Delegate:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var center: UNUserNotificationCenter!

I don't want the @available attribute to enclose the entire class - only this variable declaration.

I know that you can check availability using the following code but this is not allowed outside a function.

 if #available(iOS 10, *)  {
 } else {
 // not available
 }

Upvotes: 2

Views: 803

Answers (2)

Zell B.
Zell B.

Reputation: 10296

Availability check is not available for stored properties but it is for computed properties:

@available(iOS 10.0, *)
var center: UNUserNotificationCenter{
    return UNUserNotificationCenter.current()
}

Upvotes: 2

Robert
Robert

Reputation: 3880

You can do it like this:

 var center: UNUserNotificationCenter? {
        if #available(iOS 10, *)  {
            return UNUserNotificationCenter.current()
        } else {
            return nil
        }
    }

Upvotes: 3

Related Questions