Using @available with stored properties Using @available with stored properties ios ios

Using @available with stored properties


Here is one potential solution (thanks to blog post). The idea is to use a stored property with a type of Any and then create a computed property that will cast the stored property (and instantiate it if necessary).

private var _selectionFeedbackGenerator: Any? = nil@available(iOS 10.0, *)fileprivate var selectionFeedbackGenerator: UISelectionFeedbackGenerator {    if _selectionFeedbackGenerator == nil {        _selectionFeedbackGenerator = UISelectionFeedbackGenerator()    }    return _selectionFeedbackGenerator as! UISelectionFeedbackGenerator}

Another option is to use lazy (however, this makes the variable read-write):

@available(iOS 10.0, *)private(set) lazy var center = UNUserNotificationCenter.current()


I know this is an older question but I wanted to add an answer for people who come here via Google as I did.

As kgaidis and Cœur mentioned, you can use @available on computed properties. However, lazy variables are considered computed properties and so you can use @available on them too. This has the nice benefit of removing the boilerplate of the extra stored property and the forced casts - in fact, it leaves no evidence of the property in your pre-iOS 10 code.

You can simply declare it like this:

@available(iOS 10.0, *)private(set) lazy var center = UNUserNotificationCenter.current()

Unfortunately there's no way to make it completely read-only but the private(set) at least makes it read-only outside of the class.


@available could be used around a whole class or one or more functions, but not for properties.

Regarding your UNUserNotificationCenter usage, current returns a singleton that never changes, so why not just remove the center constant, and just use UNUserNotificationCenter.current() where center is used?


matomo