我正在尝试使用必需的便利可失败初始化程序。这是我正在使用的代码:
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)
}
我收到错误 'self' used before 'self.init' call
在 public required...
上行,并且在 try? self.init(...
上再次出现相同的错误行。
我查看了 Stack Overflow 上的其他一些相关问题。即这些:
- iOS Swift convenience initializer self used before self.init called
- 'self' used before self.init call error while using NSCoding on a custom class
所以我相应地安排了我的 convenience 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
}
关于 swift 5 : 'self' used before 'self.init' call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616338/