Beau Nouvelle Beau Nouvelle - 1 year ago 50
Swift Question

How to do an availability check on class variables

My current project supports iOS 7+ and in one of my view controllers I'm trying to use both UIAlertView and UIAlertController.

I have the #available conditional working in my methods, but I'm not sure how to wrap the vars.

When I have:

var alertController: UIAlertController!
var alertView: UIAlertView!

I get an error message telling me UIAlertController is only available in iOS 8+ and the option to 'Fix It' by "Adding @available to enclosing class". However I think this marks the entire class, and that's not what I want.

Answer Source

I just came across this issue and I too have struggled to find a solution so ended up making the variable lazy and defaulting to nil whilst adding availability annotations

For your implementation that would look as follows:

@available(iOS 8.0, *)
lazy var alertController: UIAlertController? = { return nil }()

Then whenever you try and access that property the compiler will make sure its guarded in an availability check so that you always have:

if #available(iOS 8.0, *) {
    self.alertController = ...
} else 
    self.alertView = ...