- 字典定义
let dict:[String : Any] = ["name": "王", "age": 18]; print(dict) // [Dictionary<String, Any>] let array = [["name": "李", "age": 22], ["name": "王", "age": 18]] print(array)
- 增删改
var dict:[String : Any] = ["name": "王", "age": 18, "title": "BOSS"] print(dict) // 增加 dict["height"] = 1.7 print(dict) // 修改 dict["name"] = "老李" print(dict) // 删除 dict.removeValue(forKey: "title")
- 遍历
let dict:[String : Any] = ["name": "王", "age": 18, "title": "BOSS"] for s in dict { print(s) } print("----1------") // let s: (key: String, value: Any) for s in dict { print("\(s.key) \(s.value)") } print("------2----") for (s, v) in dict { print("\(s) -- \(v)") }
- 合并
var dict1 = ["name": "王", "age": 18] as [String : Any] let dict2 = ["name": "老李", "title": "BOSS"] for (k, v) in dict2 { dict1[k] = v } print(dict1)