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?
Classes and structures (structs) are so similar in Swift that it's easy to get them confused at first, but actually there are some important underlying differences: A struct cannot inherit from another kind of struct, whereas classes can build on other classes.
In Swift, structs are value types whereas classes are reference types. When you copy a struct, you end up with two unique copies of the data. When you copy a class, you end up with two references to one instance of the data. It's a crucial difference, and it affects your choice between classes or structs.
Classes are reference types, and structs are value types. If class inheritance is not needed, structs are faster and more memory efficient. Use structs for unique copies of an object with independent states. Use structs when working with a few, relatively simple data values.
Use Classes When You Need to Control Identity Classes in Swift come with a built-in notion of identity because they're reference types. This means that when two different class instances have the same value for each of their stored properties, they're still considered to be different by the identity operator ( === ).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With