如何在Swift中使用嵌套方便的可用初始值设定项检查nil?

时间:2014-11-26 13:20:19

标签: swift initialization

class OAuthToken: NSObject, NSCoding {

var refreshToken: String?
var accessToken: String?
var scope: String?

convenience init?(refreshToken: String?, accessToken: String?, scope:String) {
    self.init()

    if let acutalRefreshToken = refreshToken as String? {
        self.refreshToken = acutalRefreshToken
    } else {
        return nil
    }
    if let actualAccessToken = accessToken as String? {
        self.accessToken = actualAccessToken
    }else {
        return nil
    }
    self.scope = scope
}

convenience init?(attributes: Dictionary<String,AnyObject>, scope: String) {
    var aRefreshToken: String!
    var anAccessToken: String?
    aRefreshToken = attributes["refresh_token"] as String?
    anAccessToken = attributes["access_token"] as String?
    let token = self.init(refreshToken: aRefreshToken, accessToken: anAccessToken, scope: scope) as OAuthToken // () is not convertible to OAuthToken
    if token != nil {
        storeInKeyChain()
    } else {
        return nil
    }
}
}

当你在另一个内部调用嵌套的可用初始值设定项时,如何检查nil的可用初始值设定项?

let token = self.init(refreshToken: aRefreshToken, accessToken: anAccessToken, scope: scope)想要返回()类型的对象,而不是可转换为我的类。我如何使用此模式并仅将对象存储到钥匙串(如果它实际上已成功创建?)

2 个答案:

答案 0 :(得分:7)

我认为当你调用超类的可用初始值设定项时,如果它失败则会有隐式返回。

事实上,关于Failable Initializers的文档指出:

  

如果由于名称空值而导致超类初始化失败,则整个初始化过程立即失败,并且不再执行初始化代码

答案 1 :(得分:5)

正如Antonio所说(+1),您不必测试其他初始化程序是否成功。如果失败,则当前初始化会立即失败。例如,考虑:

convenience init?(attributes: Dictionary<String,AnyObject>, scope: String) {
    let aRefreshToken = attributes["refresh_token"] as String?
    let anAccessToken = attributes["access_token"] as String?
    self.init(refreshToken: aRefreshToken, accessToken: anAccessToken, scope: scope)
    storeInKeyChain()
}

如果storeInKeyChain()失败,则不会调用init(refreshToken:, accessToken:, scope:)函数。请参阅The Swift Programming Language: Initialization初始化失败的传播部分。