Check for class existence in Swift

前端 未结 3 579
我寻月下人不归
我寻月下人不归 2021-02-05 05:50

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 i

相关标签:
3条回答
  • 2021-02-05 06:11

    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
        }
    
    0 讨论(0)
  • 2021-02-05 06:26

    Try this:

    if objc_getClass("NSURLQueryItem") != nil {
       // iOS 8 
    } else {
       // iOS 7
    }
    

    I've also done it like this too:

    if let theClass: AnyClass = NSClassFromString("NSURLQueryItem") {
        // iOS 8
    } else {
        // iOS 7
    }
    

    Or, you can also check system version like so, but this isn't the best practice for iOS dev - really you should check if a feature exists. But I've used this for a few iOS 7 hacks... pragmatism over purity.

        switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
        case .OrderedSame, .OrderedDescending:
            iOS7 = false
        case .OrderedAscending:
            iOS7 = true
        }
    
    0 讨论(0)
  • Simplest way I know of

    if NSClassFromString("NSURLQueryItem") != nil {
        println("NSURLQueryItem exists")
    }else{
        println("NSURLQueryItem does not exists")
    }
    
    0 讨论(0)
提交回复
热议问题