如果我在swift中有一个带有类属性的结构并且我复制了struct对象,那么是通过引用复制或传递了class属性吗?
答案 0 :(得分:17)
通过引用传递。你可以测试一下。声明:
class A{}
struct B { let a = A()}
然后:
let b = B()
print("A = \(unsafeAddressOf(b.a))")//0x0000600000019450
let b_copy = b
print("A = \(unsafeAddressOf(b_copy.a))")//0x0000600000019450
答案 1 :(得分:6)
复制结构时,会复制结构的所有属性(就像您将旧结构的每个属性分配(=
)到新结构的相应属性)无论何种类型。
当你说" class attribute"时,我假设你的意思是引用类型的变量。 (与类同名的类型表示指向该类对象的引用的引用类型。)复制引用类型(引用)的值会生成另一个指向同一对象的引用。注意"对象"不是Swift中的值 - 没有"对象类型" - 相反,对象总是通过指向它们的引用进行操作。
答案 2 :(得分:3)
我在 swift 5 中测试了上述实验: 让我们看看结果:
class A {
var id: Int
init(id: Int) {
self.id = id
}
}
struct B {
var grade: Int
var a: A
}
var a = A(id: 1)
var a_copy = a
var b1 = B(grade: 2, a: a)
var copy_b1 = b1
print(b1.a.id)
b1.a.id = 5
print(copy_b1.a.id)
print(b1.grade)
b1.grade = 3
print(copy_b1.grade)
输出:
1
5 // call by reference, same result
2
2 // call by value, no change in result
在课程上进行实验:
var a = A(id: 1)
var a_copy = a
withUnsafePointer(to: &a) { (address) in
print("address of a (class) = \(address)")
}
withUnsafePointer(to: &a_copy) { (address) in
print("address of a_copy (class) = \(address)")
}
withUnsafePointer(to: &a.id) { (address) in
print("address of a.id (struct) = \(address)")
}
withUnsafePointer(to: &a_copy.id) { (address) in
print("address of a_copy.id (struct) = \(address)")
}
输出
address of a (class) = 0x0000000114747f80
address of a_copy (class) = 0x0000000114747f88
address of a.id (struct) = 0x000060000285a390
address of a_copy.id (struct) = 0x000060000285a390
该类的两个实例都指向其属性的相同位置。
让我们在 struct 上进行实验:
print("\n\n\n")
withUnsafePointer(to: &b1) { (address) in
print("address of b1 (struct) = \(address)")
}
withUnsafePointer(to: &b1.grade) { (address) in
print("address of b1.grade (struct) = \(address)")
}
withUnsafePointer(to: &b1.a) { (address) in
print("address of b1.a (class) = \(address)")
}
withUnsafePointer(to: &b1.a.id) { (address) in
print("address of b1.a.id (class) = \(address)")
}
输出:
address of b1 (struct) = 0x0000000109382770
address of b1.grade (struct) = 0x0000000109382770
address of b1.a (class) = 0x0000000109382778
address of b1.a.id (class) = 0x0000600001e5cfd0
print("\n\n\n")
withUnsafePointer(to: ©_b1) { (address) in
print("address of copy_b1 (struct) = \(address)")
}
withUnsafePointer(to: ©_b1.grade) { (address) in
print("address of copy_b1.grade (struct) = \(address)")
}
withUnsafePointer(to: ©_b1.a) { (address) in
print("address of copy_b1.a (class) = \(address)")
}
withUnsafePointer(to: ©_b1.a.id) { (address) in
print("address of copy_b1.a.id (class) = \(address)")
}
输出:
address of copy_b1 (struct) = 0x0000000109382780
address of copy_b1.grade (struct) = 0x0000000109382780
address of copy_b1.a (class) = 0x0000000109382788
address of copy_b1.a.id (class) = 0x0000600001e5cfd0
答案 3 :(得分:1)