gpt4 book ai didi

swift - Swift 中的 Guard 对 if 给出不同的答案

转载 作者:可可西里 更新时间:2023-11-01 00:38:45 24 4
gpt4 key购买 nike

在一个比较两个链表的非常简单的程序中,我有一个递归函数来测试两个链表的当前节点是否相同,然后移动到下一个节点。

基本情况是如果两个节点都为零,我们就退出。

所以带有 if/else 的代码

是:

func compareLL(llistOne: SinglyLinkedListNode?, llistTwo: SinglyLinkedListNode?) -> Bool {
if (llistOne == nil && llistTwo == nil) { return true }
if (llistOne?.data == llistTwo?.data) {return compareLL(llistOne: llistOne?.next, llistTwo: llistTwo?.next)}
return false
}

有守卫

func compareLL(llistOne: SinglyLinkedListNode?, llistTwo: SinglyLinkedListNode?) -> Bool {
guard (llistOne != nil && llistTwo != nil) else {return true}
if (llistOne?.data == llistTwo?.data) {return compareLL(llistOne: llistOne?.next, llistTwo: llistTwo?.next)}
return false
}

那么为什么它们会产生不同的结果呢?

也就是比较两个不同的链表(不同的长度)——所以我们根据guard语句(和这不适用于 if then else 语句)。这是出乎意料的,因为我认为他们应该得到相同的结果。

我如何开发一个 guard 语句来产生与 if 模式相同的结果?

最佳答案

llistOne == nil && llistTwo == nil 的否定是 llistOne != nil || llistTwo != nil.

您的 if 仅在两个值都为 nil 时才返回。但是你的 guard 当前会在其中一个或两个都为 nil 时返回。那是不一样的。

所以把你的guard改成:

guard (llistOne != nil || llistTwo != nil) else {return true}

您可能希望继续阅读 De Morgan's Laws .

bool 逻辑的德摩根定律的基本总结是:

not(a and b) === not(a) or not(b)
not(a or b) === not(a) and not(b)

在您的情况下,allistOne == nilbllistTwo == nil

你有 a 和 b (llistOne == nil && llistTwo == nil)。所以 not(a and b)not(a) or not(b) (llistOne != nil || llistTwo != nil)

关于swift - Swift 中的 Guard 对 if 给出不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53201393/

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