在赋值期间是否通过副本传递了结构中的swift类?

时间:2022-09-05 11:50:29

If I have a struct in swift with inside a class attribute and I copy the struct object, is the class attribute copied or passed by reference?

如果我在swift中有一个struct属性并且我复制了struct对象,那么class属性是通过引用复制还是传递的?

2 个解决方案

#1


16  

Passed by reference. You can test it. Declare:

通过引用传递。你可以测试一下。宣布:

class A{}
struct B { let a = A()}

then:

然后:

let b = B()
print("A = \(unsafeAddressOf(b.a))")//0x0000600000019450
let b_copy = b
print("A = \(unsafeAddressOf(b_copy.a))")//0x0000600000019450

#2


6  

All properties of a struct are copied (as if you assigned (=) each property of the old struct to the corresponding property of the new struct) when the struct is copied, regardless of type.

在复制结构时,无论类型如何,都会复制结构的所有属性(就像将旧结构的每个属性分配(=)到新结构的相应属性一样)。

When you say "class attribute", I am assuming you mean a variable of reference type. (The type with the same name as a class denotes a reference type for references that point to objects of that class.) Copying a value of reference type (a reference) produces another reference that points to the same object. Note that "objects" are not values in Swift -- there are no "object types" -- rather, objects are always manipulated through references that point to them.

当你说“class attribute”时,我假设你的意思是引用类型的变量。 (与类同名的类型表示指向该类对象的引用的引用类型。)复制引用类型(引用)的值会生成另一个指向同一对象的引用。请注意,“对象”不是Swift中的值 - 没有“对象类型” - 相反,对象总是通过指向它们的引用进行操作。

#1


16  

Passed by reference. You can test it. Declare:

通过引用传递。你可以测试一下。宣布:

class A{}
struct B { let a = A()}

then:

然后:

let b = B()
print("A = \(unsafeAddressOf(b.a))")//0x0000600000019450
let b_copy = b
print("A = \(unsafeAddressOf(b_copy.a))")//0x0000600000019450

#2


6  

All properties of a struct are copied (as if you assigned (=) each property of the old struct to the corresponding property of the new struct) when the struct is copied, regardless of type.

在复制结构时,无论类型如何,都会复制结构的所有属性(就像将旧结构的每个属性分配(=)到新结构的相应属性一样)。

When you say "class attribute", I am assuming you mean a variable of reference type. (The type with the same name as a class denotes a reference type for references that point to objects of that class.) Copying a value of reference type (a reference) produces another reference that points to the same object. Note that "objects" are not values in Swift -- there are no "object types" -- rather, objects are always manipulated through references that point to them.

当你说“class attribute”时,我假设你的意思是引用类型的变量。 (与类同名的类型表示指向该类对象的引用的引用类型。)复制引用类型(引用)的值会生成另一个指向同一对象的引用。请注意,“对象”不是Swift中的值 - 没有“对象类型” - 相反,对象总是通过指向它们的引用进行操作。