Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for nil with nested convenience failable initializers in Swift?

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
    }
}
}

How do you check a failable initializer for nil when you call a nested failable initializer inside another?

the let token = self.init(refreshToken: aRefreshToken, accessToken: anAccessToken, scope: scope) wants to return an object of type (), not castable to my class. How can i use this pattern and only store the object to keychain if it was actually created successfully?

like image 233
bogen Avatar asked Nov 26 '14 13:11

bogen


1 Answers

I think that when you call a failable initializer of a superclass, it has an implicit return if it fails.

In fact the documentation about Failable Initializers states that:

If the superclass initialization fails because of an empty name value, the entire initialization process fails immediately and no further initialization code is executed

like image 176
Antonio Avatar answered Oct 15 '22 15:10

Antonio