Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @available to create a class conditionally

Tags:

ios

swift

I have a use case where it would be incredibly useful to create two implementations of a class: one for iOS 7 and below, and a second for 8+. It seems like @available is the tool I'm looking for, but I can't figure out how to make it work.

From the documentation it seems like this should be possible:

@available(iOS 8.0, unavailable)
class MyCompatabilityClass : NSObject {
    //iOS 7 implementation
}

@available(iOS 8.0, *)
class MyCompatabilityClass : ClassOnlyAvailableInIOS8 {
    //iOS 8 implementation
}

But I am getting an Expected version number error on @available(iOS 8.0, unavailable). A conditional class for iOS version above a specified version works fine, but how can I specify a class which is only compiled below a certain version number?

like image 487
sak Avatar asked Oct 28 '15 14:10

sak


1 Answers

You cannot undeclare the existence of a class, but you can deprecate it.

Also, you cannot declare the same class twice, so your newer class will have to have a different name.

Thus:

@available(iOS, introduced=7.0, deprecated=8.0, message="Use MyCompatibilityClass2, please!")
class MyCompatabilityClass : NSObject {
    //iOS 7 implementation
}

@available(iOS 8.0, *)
class MyCompatabilityClass2 : NSObject { // or whatever the superclass is
    //iOS 8 implementation
}
like image 84
matt Avatar answered Oct 23 '22 06:10

matt