Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for class existence in Swift

Tags:

ios

swift

I want to use NSURLQueryItem in my Swift iOS app. However, that class is only available since iOS 8, but my app should also run on iOS 7. How would I check for class existence in Swift?

In Objective-C you would do something like:

if ([NSURLQueryItem class]) {
    // Use NSURLQueryItem class
} else {
    // NSURLQueryItem is not available
}

Related to this question is: How do you check for method or property existence of an existing class?

There is a nice section in https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AdvancedAppTricks/AdvancedAppTricks.html#//apple_ref/doc/uid/TP40007072-CH7-SW4 called Supporting Multiple Versions of iOS, which explains different techniques for Objective-C. How can these be translated to Swift?

like image 464
Florian Avatar asked Aug 14 '14 11:08

Florian


2 Answers

Swift 2.0 provides us with a simple and natural way to do this.It is called API Availability Checking.Because NSURLQueryItem class is only available since iOS8.0,you can do in this style to check it at runtime.

    if #available(iOS 8.0, *) {
        // NSURLQueryItem is available

    } else {
        // Fallback on earlier versions
    }
like image 187
tounaobun Avatar answered Oct 19 '22 16:10

tounaobun


Simplest way I know of

if NSClassFromString("NSURLQueryItem") != nil {
    println("NSURLQueryItem exists")
}else{
    println("NSURLQueryItem does not exists")
}
like image 15
Sean Avatar answered Oct 19 '22 14:10

Sean