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
的值保持不变?
答案 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