先上代码
struct Person: CustomStringConvertible {
var name: String
var age: Int
var description: String {
"Struct name:\(name), age:\(age)"
}
}
var structArrayDict: [String: [Person]] = [:]
var structArray: [Person] = []
structArray.append(Person(name: "Peter", age: 15))
structArrayDict["Person"] = structArray
// 字典中的数组添加一个元素
structArrayDict["Person"]?.append(Person(name: "Jerry", age: 5))
//等同于
var personStructArray = structArrayDict["Person"]
personStructArray?.append(Person(name: "Jerry", age: 5))
structArrayDict["Person"] = personStructArray
print(structArrayDict)
输出 ["Person": [Struct name:Peter, age:15, Struct name:Jerry, age:5]]
在OC中 数组与字典等容器是引用类型,而在Swift中容器是值类型。
所以var personStructArray = structArrayDict["Person"]
这样的代码其实是Copy了一个全新数组与字典中的数组只是元素相同。
再来探讨Struct 与 Class的值类型与引用类型区别
//等同于
var personStructArray = structArrayDict["Person"]
personStructArray?.append(Person(name: "Jerry", age: 5))
structArrayDict["Person"] = personStructArray
var peter = personStructArray?[0]
peter?.age = 16
输出 ["Person": [Struct name:Peter, age:15, Struct name:Jerry, age:5]]
因为Peter是Struct是一个值类型,无法通用引用修改,var Peter 是复制的一份全新的Person结构体。
class Student: CustomStringConvertible {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
var description: String {
"Class name:\(name), age:\(age)"
}
}
var classArrayDict: [String: [Student]] = [:]
var classArray: [Student] = []
classArray.append(Student(name: "Herry", age: 12))
classArrayDict["Student"] = classArray
var studentClassArray = classArrayDict["Student"]
studentClassArray?.append(Student(name: "Jimmy", age: 18))
classArrayDict["Student"] = studentClassArray
var herry = studentClassArray?[0]
herry?.age = 13
print(classArrayDict)
输出 ["Student": [Class name:Herry, age:13, Class name:Jimmy, age:18]]
这里var herry 是class对象引用类型,所以herry变量与数组中的index为0的对象指向同一个位置的内存数据。