检查Swift中是否存在类 [英] Check for class existence in Swift

查看:165
本文介绍了检查Swift中是否存在类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Swift iOS应用程序中使用NSURLQueryItem。但是,该类仅在iOS 8中可用,但我的应用程序也应在iOS 7上运行。如何在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?

在Objective-C中你会做类似的事情:

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?

https://developer.apple.com/library/ios /documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AdvancedAppTricks/AdvancedAppTricks.html#//apple_ref/doc/uid/TP40007072-CH7-SW4 名为 支持多个iOS版本 ,这解释了不同Objective-C的技术。如何将这些转换为Swift?

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?

推荐答案

Swift 2.0为我们提供了一种简单而自然的方法来实现这一点。它被称为API可用性检查。因为 NSURLQueryItem 类仅在iOS8.0之后可用,您可以使用此样式在运行时检查它。

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
    }

这篇关于检查Swift中是否存在类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆