swift 2.0 @available不起作用

时间:2015-10-05 12:29:15

标签: ios xcode swift swift2 ios9

我正在尝试在iOS7上运行此代码,但它失败了

@available(iOS 9.0, *)
class WatchConnection: NSObject, WCSessionDelegate {

    class func sharedInstance() -> WatchConnection {
        struct WatchConnectionSingleton {
            static let instance = WatchConnection()
        }
        return WatchConnectionSingleton.instance
    }

    override init() {
        super.init()
        if (WCSession.isSupported()) {
            let session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()
        }
    }

enter image description here

enter image description here

但这有效

import WatchKit
import WatchConnectivity

class WatchConnection: NSObject, WCSessionDelegate {

    class func sharedInstance() -> WatchConnection {
        struct WatchConnectionSingleton {
            static let instance = WatchConnection()
        }
        return WatchConnectionSingleton.instance
    }

    override init() {
        super.init()
        guard #available(iOS 9.0, *) else { return }

        if (WCSession.isSupported()) {
            let session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()
        }
    }

    // use with invalidated session
    @available(iOS 9.0, *)
    func getUserId(completion: ((String?) -> Void)?) {

1 个答案:

答案 0 :(得分:4)

您无法在iOS 7中使用@available

您可以使用以下方法检查版本:

if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0) {
    //For iOS 7 or less
}
else{
    //Check for available 
}

检查documents

另请在此处查看此article中描述的内容。

Swift 2.1 Documents有类似#available的语法。请检查预发布documents

关于守卫陈述条件:

如果不满足一个或多个条件,则使用保护语句将程序控制转移到范围之外。