![](/img/trans.png)
[英]Swift: Convenience initializers - Self used before self.init call
[英]Swift 5: 'self' used before 'self.init' call
我正在嘗試使用所需的便利的可失敗初始化程序。 這是我正在使用的代碼:
public init(authState: OIDAuthState, config: [String: String], accessibility: CFString = kSecAttrAccessibleWhenUnlockedThisDeviceOnly) throws {
self.authState = authState
self.config = config
self.accessibility = accessibility
super.init()
KeycloakAuth.configuration = config
}
public required convenience init?(coder aDecoder: NSCoder) {
try? self.init(authState: aDecoder.decodeObject(forKey: "authState") as! OIDAuthState,
config: aDecoder.decodeObject(forKey: "config") as! [String: String],
accessibility: aDecoder.decodeObject(forKey: "accessibility") as! CFString)
}
我在public required...
行上'self' used before 'self.init' call
了錯誤'self' used before 'self.init' call
, try? self.init(...
再次出現相同的錯誤try? self.init(...
try? self.init(...
行。
我在 Stack Overflow 上查看了其他一些相關問題。 即這些:
因此,我相應地安排了我的便利 init 以嘗試在出現任何問題時返回 nil:
public required convenience init?(coder aDecoder: NSCoder) {
guard
let authState = aDecoder.decodeObject(forKey: "authState") as? OIDAuthState,
let config = aDecoder.decodeObject(forKey: "config") as? [String: String]
else {
print("KeycloakTokenManager: There was an error intializing authState or config")
return nil
}
let accessibility = aDecoder.decodeObject(forKey: "accessibility") as! CFString
try? self.init(authState: authState, config: config, accessibility: accessibility)
}
但是我在相同的代碼(初始化程序,並調用self.init
)上遇到了相同的錯誤。 有趣的是,我的項目在 Swift 4 上構建得很好,但我沒有聽說過任何關於這是 Swift 5 的錯誤。我怎樣才能擺脫這個錯誤?
一個解決方案是不調用指定的初始化程序
public required init?(coder aDecoder: NSCoder) {
guard
let authState = aDecoder.decodeObject(forKey: "authState") as? OIDAuthState,
let config = aDecoder.decodeObject(forKey: "config") as? [String: String]
else {
print("KeycloakTokenManager: There was an error intializing authState or config")
return nil
}
self.authState = authState
self.config = config
self.accessibility = aDecoder.decodeObject(forKey: "accessibility") as! CFString
super.init()
KeycloakAuth.configuration = config
}
這是我剛剛發現的另一個解決方案也有效。 因為初始化器沒有拋出,最終的代碼可以是這樣的:
public init(authState: OIDAuthState, config: [String: String], accessibility: CFString = kSecAttrAccessibleWhenUnlockedThisDeviceOnly) {
self.authState = authState
self.config = config
self.accessibility = accessibility
super.init()
KeycloakAuth.configuration = config
}
public required convenience init?(coder aDecoder: NSCoder) {
self.init(authState: aDecoder.decodeObject(forKey: "authState") as! OIDAuthState,
config: aDecoder.decodeObject(forKey: "config") as! [String: String],
accessibility: aDecoder.decodeObject(forKey: "accessibility") as! CFString)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.