How to check for null with nested handy bad 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 for a failed initializer for nil when you call a nested initializer with initialization inside another?

the let token = self.init(refreshToken: aRefreshToken, accessToken: anAccessToken, scope: scope) wants to return an object of type () that cannot be used for my class. How can I use this template and only store an object in a chain of bundles if it was actually created successfully?

+6
source share
2 answers

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

In fact, he documentation on Failable Initializers claims that:

If the initialization of the superclass fails due to the null value of the name, the entire initialization process fails and no further initialization code is executed

+6
source

As Antonio (+1) says, you don’t need to check if another initializer succeeded or not. If this fails, your current initialization will fail. For example, consider:

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

The storeInKeyChain() function is not called if init(refreshToken:, accessToken:, scope:) fails. See Section Deploying the Initialization Section. Quick Programming Language: Initialization .

+3
source

Source: https://habr.com/ru/post/978728/


All Articles