-2
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

With copy-on-write no new object is created until we mutate the object copied. Why does the value of numberOfCard remain the same after I changed the value of cardTwo property?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • That's because you are not instantiating another object but copying the properties of the object to another object. This is what I understand. – Maihan Nijat Jun 02 '18 at 16:28
  • Why do you expect the `numberOfCards` property value to change when you set the `identity` property value? – rmaddy Jun 02 '18 at 16:30

1 Answers1

0

yes! actually my question seems twisted and meaningless, sorry :( I've made confusion when in a particular situation (this is not that situation :) ) you have to implement copy-on-write functionality for your own data type for example when a struct contain a mutable reference but should still retain value semantics

Maybe the code below could explain what i was trying to make (even though meaningless :) ) thanks for your answer ;)

    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
  • So basically entire question and answer is duplicate of https://stackoverflow.com/questions/32984258/how-can-i-make-a-container-with-copy-on-write-semantics-swift – matt Jun 04 '18 at 15:12