在结构上保留值语义(包含引用类型的数组)

时间:2018-12-18 16:09:19

标签: swift struct value-type

说(举个例子),我有一个类 Person 和一个结构 House

class Person {
    var name: String
    var lastName: String

    init(name: String, lastName: String) {
        self.name = name
        self.lastName = lastName
    }
}

struct House {
    var address: String
    var squareMeters: Float
    var owner: Person

    init(withAddress address: String, squareMeters: Float, andOwner owner: Person) {
        self.address = address
        self.squareMeters = squareMeters
        self.owner = owner
    }
}
在这种情况下,

House 上保留值语义很容易,如果我没记错的话,我可以做类似的事情:

struct House {
    var address: String
    var squareMeters: Float
    private var owner: Person //owner is now private

    init(withAddress address: String, squareMeters: Float, andOwner owner: Person) {
        self.address = address
        self.squareMeters = squareMeters
        //init now creates a copy of the owner passed
        self.owner = Person(name: owner.name, lastName: owner.lastName)
    }

    //every time the owner gets modified from the outside we make sure to create a copy if needed
    private var ownerToWrite: Person {
        mutating get {
            if !isKnownUniquelyReferenced(&owner) {
                owner = Person(name: owner.name, lastName: owner.lastName)
            }
            return owner
        }
    }

    var ownerName: String {
        get {
            return owner.name
        }
        mutating set {
            ownerToWrite.name = newValue
        }
    }

    var ownerLastName: String {
        get {
            return owner.name
        }
        mutating set {
            return ownerToWrite.lastName = newValue
        }
    }
}

好的,这应该可行。但是,如果 House 包含 Person 数组,该怎么办?例如:

struct House {
    var address: String
    var squareMeters: Float
    var tenants: [Person]

    init(withAddress address: String, squareMeters: Float, andTenants tenants: [Person]) {
        self.address = address
        self.squareMeters = squareMeters
        self.tenants = tenants
    }
}

如何在新的 House 结构上维护值语义?预先谢谢你。

0 个答案:

没有答案