为什么在copyOnWrite期间不会更新type属性

时间:2018-06-02 16:25:26

标签: swift

struct Card: CustomStringConvertible {
    var identity:Int

    var description: String {
        return "card:\(identity)"
    }

    static var numberOfCards = 0

    init(identity:Int) {
        Card.numberOfCards += 1
        self.identity = identity
    }
}

var cards = [Card]()

let cardOne = Card(identity: 1)
var cardTwo = cardOne //card:1
Card.numberOfCards // 1
cardTwo.identity = 2 // card:2
Card.numberOfCards // 1

使用copy-on-write,在我们改变复制的对象之前,不会创建新对象。更改numberOfCard属性的值后,为什么cardTwo的值保持不变?

1 个答案:

答案 0 :(得分:0)

是的!实际上我的问题似乎是扭曲和毫无意义的,抱歉:(在特定情况下,我已经混淆了(这不是那种情况:))你必须为自己的数据类型实现写时复制功能,例如当一个struct包含一个可变引用,但仍应保留值语义

也许下面的代码可以解释我想要做的事情(尽管毫无意义:) :)感谢您的回答;)

    class Identifier {

        static var instanceNumbers = 0

        var identity:Int

        init(identity:Int) {
            Identifier.instanceNumbers += 1
            self.identity = identity
        }
    }

    struct Card: CustomStringConvertible {

        private var _id:Identifier

        var id:Identifier {
            mutating get {
                if !isKnownUniquelyReferenced(&_id){
                    let identity = _id.identity
                    _id = Identifier(identity: identity)
                }
                return _id
            }
        }

        init(id:Identifier){
            self._id = id
        }

        var description: String {
            return "card:\(_id.identity)"
        }
    }

    let cardOne = Card(id: Identifier(identity: 1))
    let cardTwo = Card(id: Identifier(identity: 2))
    Identifier.instanceNumbers // 2
    var cardThree = cardTwo
    Identifier.instanceNumbers // 2
    cardThree.id.identity = 3
    Identifier.instanceNumbers // 3