为什么我不能在指定的时间点返回self

indirect enum BinarySearchTree<E: Comparable> {
    case leaf
    case node(BinarySearchTree<E>, E, BinarySearchTree<E>)

    mutating func insert(_ e: E) {
        switch self {
        case .leaf:
            self = .node(.leaf, e, .leaf)
        case .node(var left, let v, var right):
            if e < v { left.insert(e) }
            if e > v { right.insert(e) }
            self = .node(left, v, right)
            // Why can't I just return self here? e == v, so isn't it already a .node(left, v, right)?
        }
    }
}

当我运行以下代码时,返回self

var bst = BinarySearchTree<Int>()
bst.insert(3)
bst.insert(5)

程序只是停留在它的初始化阶段,

.node(leaf, 3, leaf)

谢谢!

推荐答案

您需要使用self = .node(left, v, right)的原因是因为在这一点上,self等于(.leaf, 3, .leaf).局部变量right刚刚被更新为(.leaf, 5, .leaf).

更新局部变量right不会直接更新self‘S right.因此,您需要用self = .node(left, v, right)来结束case,以更新其right值(或其left值,视情况而定).

您可以通过在两个if语句之后添加以下行来确认这一点:

print("After insert: self = \(self), right = \(right)")

这将打印以下内容:

插入后:Self=node(__lldb_expr_53.BinarySearchTree<;Swift.Int>;.leaf,3,__lldb_expr_53.BinarySearchTree<;Swift.Int>;.leaf),Right=node(__lldb_expr_53.BinarySearchTree<;Swift.Int>;.leaf,5,__lldb_expr_53.BinarySearchTree<;Swift.Int>;.leaf)

如你所见,self‘S right还没有更新.仅更新了局部变量right.

以下是switch声明的一个更明确的版本,可能会让它变得更清楚:

switch self {
    case .leaf:
        self = .node(.leaf, e, .leaf)
    case .node(var left, let v, var right):
        if e < v {
            left.insert(e)
            self = .node(left, v, right)
        } else if e > v {
            right.insert(e)
            self = .node(left, v, right)
        }
}

你不需要在When e == v中做任何事情,只需要在更新leftright之后更新self.

Swift相关问答推荐

如何让CTFontCreateUIFontForLanguage与汉字和表情包协同工作?

OBJC代码中Swift 演员的伊瓦尔:原子还是非原子?

编写Swift字符串的属性包装时遇到问题

文件命名&NumberForMatter+扩展名&:含义?

与视图交互使工具栏&;标题消失

为什么这个快速代码不显示文本字段?

如何在 Vapor 中制作可选的查询过滤器

Swift UI中视图上的值未更新

如何让默认函数参数引用另一个函数参数?

从一个范围减go 多个范围

使用 swift 的 Firebase 身份验证

如何在不将变量转换为字符串的情况下判断变量在 Swift 中是否为 Optional(nil)?

在主要参与者中启动分离任务和调用非隔离函数之间的区别

数组使用偏移量对自身执行 XOR

Xcode 13.3 将函数调用更改为属性访问

在 Xcode 中自动实现 Swift 协议方法

CMutablePointer - 如何访问它?

如何在Swift中找出字母是字母数字还是数字

更改在变量的 willSet 块中设置的值

Swift 5 秒后关闭 UIAlertView