简体   繁体   English

Swift:如果将引用类型常量分配给变量,但该变量发生了变化,会发生什么情况?

[英]Swift: What happens when a reference type constant is assigned to a variable, but that variable changes?

I am confused on the difference between var and let for reference type in swift.我对 swift 中引用类型的 var 和 let 之间的区别感到困惑。

In the code below, let head is assigned to var current:在下面的代码中,让 head 分配给 var current:

 public class ListNode {
     public var val: Int
     public var next: ListNode?
     public init() { self.val = 0; self.next = nil; }
     public init(_ val: Int) { self.val = val; self.next = nil; }
     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 }

var current = ListNode()
let head = current

current.next = ListNode(3)
current = current.next!

print(current.val) -> return "3"
print(head.val)  -> return "0"
print(head.next?.val) -> return "3"

I don't understand why head.val = 0 and head.next.val = 3 in the end.我不明白为什么 head.val = 0 和 head.next.val = 3 最后。

I understand that head and current are an instance of a class, therefore they are reference type.我知道 head 和 current 是 class 的一个实例,因此它们是参考类型。 They are supposed to be point to the exact same memory address.它们应该指向完全相同的 memory 地址。 But it is very confusing to me why但这让我很困惑为什么

current = current.next!当前=当前。下一个!

Doesn't make head also equal to current.next.不会使 head 也等于 current.next。

Does't head and current point to the same memory address?头和电流不是指向同一个 memory 地址吗? why can they be different values?为什么它们可以是不同的值? If someone tell me, head can't change value because it is a constant, then why does head.next?.val changed to 3?如果有人告诉我, head 不能改变值,因为它是一个常数,那么为什么 head.next?.val 改为 3?

The answer must be so obvious, because I don't see anyone asking this question.答案一定很明显,因为我没有看到有人问这个问题。 But I am just so lost.但我只是迷路了。 Thank you!谢谢!

You expect reference type variables to work like pointers, but they don't.您希望引用类型变量像指针一样工作,但事实并非如此。 Reference types ensure that if you change a property of a specific instance, that change will be reflected for all other references to the same instance as well.引用类型确保如果您更改特定实例的属性,该更改也将反映到对同一实例的所有其他引用。

However, when you change the instance that a mutable reference points to, that won't change won't propagate to other references pointing to the original instance.但是,当您更改可变引用指向的实例时,不会更改的实例不会传播到指向原始实例的其他引用。 The other references will still point to the original instance.其他引用仍将指向原始实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM