如何在iOS中声明全局变量之前进行可用性检查?

时间:2017-06-16 15:41:47

标签: ios swift swift3 compatibility

在声明 center 变量之前,我需要在我的应用中检查iOS 10的可用性。

这是我的App代表:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var center: UNUserNotificationCenter!

我不希望@available属性包含整个类 - 只包含此变量声明。

我知道您可以使用以下代码检查可用性,但在函数外部不允许这样做。

 if #available(iOS 10, *)  {
 } else {
 // not available
 }

2 个答案:

答案 0 :(得分:2)

你可以这样做:

 var center: UNUserNotificationCenter? {
        if #available(iOS 10, *)  {
            return UNUserNotificationCenter.current()
        } else {
            return nil
        }
    }

答案 1 :(得分:1)

可用性检查不适用于存储的属性,但它适用于计算属性:

@available(iOS 10.0, *)
var center: UNUserNotificationCenter{
    return UNUserNotificationCenter.current()
}