测试数据
class ObjModel: NSObject {
var name: String = "name1"
var age: Int = 0
var sex: Bool = false
init(name: String, age: Int, sex: Bool) {
self.name = name
self.age = age
self.sex = sex
}
}
let objModel1 = ObjModel(name: "name1", age: 1, sex: true)
let objModel2 = ObjModel(name: "name2", age: 2, sex: false)
let objModel3 = ObjModel(name: "name3", age: 3, sex: true)
let objModel4 = ObjModel(name: "name4", age: 2, sex: false)
let objArr: [ObjModel] = [objModel1, objModel2, objModel3, objModel4]
var objArr2 = objArr
objArr2.remove(at: 0)
print("11111")
print(objArr.description)
print("22222")
print(objArr2.description)
//打印
/*
11111
[<swift常规测试.ObjModel: 0x60000299d0b0>,
<swift常规测试.ObjModel: 0x60000299b2d0>,
<swift常规测试.ObjModel: 0x60000299b2a0>,
<swift常规测试.ObjModel: 0x60000299b300>]
22222
[<swift常规测试.ObjModel: 0x60000299b2d0>,
<swift常规测试.ObjModel: 0x60000299b2a0>,
<swift常规测试.ObjModel: 0x60000299b300>]
结论
objArr中有4个元素,将objArr赋值给objArr2,删除objArr2中一个元素后,objArr还是有4个元素,说明值类型的Array赋值是重新拷贝的一份。
然而,里面的对象地址没变,说明数组里的元素还是指向相同的对象,没有拷贝出新的地址,这样的情况就会是,无论操作哪个数组的元素属性,都是操作的同一个对象,这就是引用类型的特点。