深copy & 浅copy
- 浅拷贝(copy):是对于一个对象的顶层拷贝,拷贝父对象,不会拷贝对象的内部的子对象
- 深拷贝(deepcopy): 是对于一个对象所有层次的拷贝(递归),完全拷贝了父对象及其子对象
class Person {
var name: String = "name1"
}
struct Student {
let p = Person()
}
var student1 = Student()
var student2 = student1
student2.p.name = "name2"
print(student1.p.name)
// name2
print(student2.p.name)
// name2
这就是明显的浅copy, student2.p属性copy的就是指针,修改student2.p会影响到student1.p
我们copy时需要对person属性特殊处理,如果有很多像person类这样的属性,或者有3级引用属性,我们的代码就会臃肿
系统函数isKnownUniquelyReferenced(_:)
func isKnownUniquelyReferenced<T>(_ object: inout T) -> Bool where T : AnyObject
返回值
如果是对象包含强引用属性,则为false,否则为true
参数
类的实例,此函数不修改对象。
用法
isKnownUniquelyReferenced(_:)
函数对于实现值类型的深度存储的写时复制优化非常有用:
struct Student {
private var _p = Person()
var p: Person {
mutating get {
if isKnownUniquelyReferenced(&self._p) {
return self._p
} else {
let newP = Person()
newP.name = _p.name
_p = newP
return _p
}
} set {
_p = newValue
}
}
}