简体   繁体   中英

Functions, Structs and Value Semantics in Swift

If a struct has a function which contains an object, does the struct retain value semantics? Example:

struct MyStruct {
    var x = 3

    func setX() {
        let y = NSNumber(value: 2)
        x = y.intValue
    }
}

The struct doesn't have any members with reference so it should have value semantics. Does the fact that the function setX() has a reference member y cause MyStruct to use reference semantics?

Structs with mutating functions retain the same value semantics as any other structs.

Calling setX would mutate the instance it was called on, but NOT any other instances, as they would be distinct copied instances, and not a shared instance (as with reference types).

You can see for yourself in this example :

struct Counter {
    var count: Int

    mutating func increment() {
        count += 1
    }
}

var x = Counter(count: 0)
let y = x // a copy is made

print("x: \(x)") // x: Counter(count: 0)
print("y: \(y)") // y: Counter(count: 0)

x.increment()

print("x: \(x)") // x: Counter(count: 1), method target affected
print("y: \(y)") // y: Counter(count: 0), copy unaffected

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