Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are swift classes inside struct passed by copy during assignment?

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?

like image 612
Nisba Avatar asked Dec 08 '16 17:12

Nisba


People also ask

Can a class inherit from a struct Swift?

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.

What are the main differences between classes and structs in Swift?

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.

Which is faster struct or class in Swift?

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.

When should you use classes over structs Swift?

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 ( === ).


2 Answers

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
like image 161
Andrey Chernukha Avatar answered Oct 04 '22 03:10

Andrey Chernukha


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.

like image 25
newacct Avatar answered Oct 04 '22 02:10

newacct