gpt4 book ai didi

swift - 在 Swift 中将可选绑定(bind)转换为错误处理的过程是怎样的?

转载 作者:行者123 更新时间:2023-11-30 11:22:13 26 4
gpt4 key购买 nike

我正在学习使用 Locksmith 框架来存储 token 的 OAuth 教程。本教程是用旧版本的 Swift 和旧版本的 Locksmith 框架编写的。在 Swift 4 中重新创建示例时,我注意到 Locksmith 4.0 使用 do try catch block 进行错误处理。我正在尝试将教程的可选绑定(bind)转换为使用框架的错误处理方法。我首先自己尝试过,但我很难理解为什么教程使用可选绑定(bind)。

以下是教程摘录:

var OAuthToken: String?
{
set
{
if let valueToSave = newValue
{
let error = Locksmith.saveData(["token": valueToSave], forUserAccount: "github")
if let errorReceived = error
{
Locksmith.deleteDataForUserAccount("github")
}
addSessionHeader("Authorization", value: "token \(newValue)")
}
else // they set it to nil, so delete it
{
Locksmith.deleteDataForUserAccount("github")
removeSessionHeaderIfExists("Authorization")
}
}
get
{
// try to load from keychain
let (dictionary, error) = Locksmith.loadDataForUserAccount("github")
if let token = dictionary?["token"] as? String {
return token
}
removeSessionHeaderIfExists("Authorization")
return nil
}
}

这是我所拥有的。我相信我滥用了与可选绑定(bind)相关的 catch 语句:

var OAuthTokenCompletionHandler: ((NSError?) -> Void)?

var authToken: String? {
set {
if let valueToSave = newValue{
do{
try Locksmith.saveData(data: ["token" : valueToSave], forUserAccount: "AzureMediaServices")
} catch {
//could not save the data into keychain
//handle the error somehow
try Locksmith.deleteDataForUserAccount(userAccount: "AzureMediaServices")
}

addSessionHeader("Authorization", value: "Bearer \(valueToSave)")
} else {
//try to set it to nil
removeSessionHeaderIfExists("Authorization")
}
}
get {
//TODO: implement
}
}

最佳答案

我认为这里的主要问题是原始代码没有处理Locksmith.deleteDataForUserAccount的任何错误状态。 Locksmith.deleteDataForUserAccount 被调用两次,并且这个计算属性变得相当复杂。如果这两个函数调用的错误处理相同,我建议将其提取到辅助函数中。

这是我的第一次尝试:

var OAuthTokenCompletionHandler: ((NSError?) -> Void)?

var authToken: String? {
set {
guard let valueToSave = newValue else {
do {
try Locksmith.deleteDataForUserAccount(userAccount: "AzureMediaServices")
}
catch {
// handle the error somehow
}

removeSessionHeaderIfExists("Authorization")
return
}

do{
try Locksmith.saveData(data: ["token" : valueToSave], forUserAccount: "AzureMediaServices")
} catch {
do {
try Locksmith.deleteDataForUserAccount(userAccount: "AzureMediaServices")
}
catch {
// handle the error somehow
}
}

addSessionHeader("Authorization", value: "Bearer \(valueToSave)")
}
get {
guard let token = Locksmith.loadDataForUserAccount("github")?["token"] as? String {
removeSessionHeaderIfExists("Authorization")
return nil
}
return token
}
}

关于swift - 在 Swift 中将可选绑定(bind)转换为错误处理的过程是怎样的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51142625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com