Type value types in Swift

I understand the difference between Value Types and Link Types. I know that Structures are Value Types, and according to the Swift documentation, all values ​​stored in the structure are themselves value types. Now my question is, if I have a stored property in Struct, which is an instance of the class. In this case, will the whole class be copied or just its address?

Any help would be appreciated.

+5
source share
2 answers

It copies the pointer to the instance. I just experienced it in the playground.

struct MyStruct { var instance: MyClass } class MyClass { var name: String init(name: String) { self.name = name println("inited \( self.name )") // Prints "inited Alex" only once } } var foo = MyClass(name: "Alex") // make just one instance var a = MyStruct(instance: foo) // make a struct that contains that instance var b = a // copy the struct that references the instance foo.name = "Wayne" // Update the instance // Check to see if instance was updated everywhere. a.instance.name // Wayne b.instance.name // Wayne 

What is different is that now there are two different links to the same object. Therefore, if you change one structure to another instance, you only hang it for this structure.

 b.instance = MyClass(name: "Vik") // a and b no longer reference the same instance a.instance.name // Wayne b.instance.name // Vik 

A playground is a great way to check such questions. I did not know the answer completely when I read this question. But now I am :)

So do not be afraid to play.

+8
source

I think you are reading the documentation incorrectly. According to Swift Programming,

All structures and enumerations are value types in Swift. This means that any instances of structure and enumeration you create - and any types of values ​​that they have as properties , are always copied when they are passed in your code.

Because classes are reference types, not value types, they are not copied, even if they are value type properties, so only the address is copied.

+2
source

Source: https://habr.com/ru/post/1200616/


All Articles