gpt4 book ai didi

swift - 我如何判断哪个守卫声明失败了?

转载 作者:IT王子 更新时间:2023-10-29 05:18:55 24 4
gpt4 key购买 nike

如果我有一堆链式 guard let 语句,除了将我的 guard let 分解成多个语句外,我如何诊断哪个条件失败了?

给出这个例子:

guard let keypath = dictionary["field"] as? String,
let rule = dictionary["rule"] as? String,
let comparator = FormFieldDisplayRuleComparator(rawValue: rule),
let value = dictionary["value"]
else
{
return nil
}

我如何判断 4 个 let 语句中的哪一个失败并调用了 else block ?

我能想到的最简单的事情是将语句分解为 4 个连续的 guard else 语句,但感觉不对。

 guard let keypath = dictionary["field"] as? String
else
{
print("Keypath failed to load.")

self.init()
return nil
}

guard let rule = dictionary["rule"] as? String else
{
print("Rule failed to load.")

self.init()
return nil
}

guard let comparator = FormFieldDisplayRuleComparator(rawValue: rule) else
{
print("Comparator failed to load for rawValue: \(rule)")

self.init()
return nil
}

guard let value = dictionary["value"] else
{
print("Value failed to load.")

self.init()
return nil
}

如果我想将它们全部放在一个 guard 语句中,我可以想到另一种选择。检查 guard 语句中的 nils 可能会起作用:

guard let keypath = dictionary["field"] as? String,
let rule = dictionary["rule"] as? String,
let comparator = FormFieldDisplayRuleComparator(rawValue: rule),
let value = dictionary["value"]
else
{

if let keypath = keypath {} else {
print("Keypath failed to load.")
}

// ... Repeat for each let...
return nil
}

我什至不知道这是否会编译,但我还不如使用一堆 if let 语句或 guard 开始。

什么是惯用的 Swift 方式?

最佳答案

Erica Sadun 刚刚就这个主题写了一篇不错的博文。

她的解决方案是劫持 where 子句并使用它来跟踪哪些 guard 语句通过。使用 diagnose 方法的每个成功的保护条件都会将文件名和行号打印到控制台。最后一个 diagnose 打印语句之后的警戒条件是失败的条件。解决方案如下所示:

func diagnose(file: String = #file, line: Int = #line) -> Bool {
print("Testing \(file):\(line)")
return true
}

// ...

let dictionary: [String : AnyObject] = [
"one" : "one"
"two" : "two"
"three" : 3
]

guard
// This line will print the file and line number
let one = dictionary["one"] as? String where diagnose(),
// This line will print the file and line number
let two = dictionary["two"] as? String where diagnose(),
// This line will NOT be printed. So it is the one that failed.
let three = dictionary["three"] as? String where diagnose()
else {
// ...
}

可以找到 Erica 关于此主题的文章 here

关于swift - 我如何判断哪个守卫声明失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37664340/

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