不应该`init(重复:计数)`通过引用工作?

时间:2018-02-20 21:38:39

标签: arrays swift reference initialization

我在游乐场尝试了这段代码:

var a = [String](repeating: String(), count: 2)
a[0] = "string"
a[1]

最后一行打印a[1] ""的内容。

不应该是"string",因为我将对象的引用传递给数组a的构造函数?

这是否意味着创建了2个String类型的对象而不是仅重复了2次?

编辑:

正如用户所指出的那样,我正在寻找的行为通过以下代码再现

import UIKit

class A {
    var str = "str"
}

var a = [A](repeating: A(), count: 2)
a[0].str = "a"
Swift.print(a[1].str) //this prints "a"

1 个答案:

答案 0 :(得分:2)

首先,您没有传递参考。所有字符串都是值类型(不是引用类型)。它们总是被复制。

即使你传递了一个引用,它也是一个初始值。为a[0]分配新引用不会更改引用的内容。

要查看引用的行为,让我们声明一个真正的引用类型:

class RefType {
    var value: String

    init(_ value: String) {
        self.value = value
    }
}

var a = [RefType](repeating: RefType("x"), count: 2)
// the same reference in both indices
print(a[0].value) //x
print(a[1].value) //x

// let's change the value of the reference
a[0].value = "y"
// still the same reference in both indices
print(a[0].value) //y
print(a[1].value) //y

// let's change one of the references to a new object
a[0] = RefType("z")
print(a[0].value) //z
print(a[1].value) //y