简体   繁体   中英

Struct value types in Swift

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

Any help would be appreciated.

It copies the pointer to the instance. I just tested this in a 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 though, is that it's now two different references to the same object. So if you change one struct to a different instance, you are only hanging it for that struct.

b.instance = MyClass(name: "Vik")

// a and b no longer reference the same instance
a.instance.name // Wayne
b.instance.name // Vik

The playground is a great way to test out questions like these. I did not know the answer definitively when I read this question. But now I do :)

So don't be afraid to go play.

I think you misread the documentation. According to the The Swift Programming Language,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM