//1.如何定义字典 //1> 定义不可变字典:使用let修饰 //编译器会根据[]中每一个元素(数组),还是健值队(字典) //写法一 let dict3 : Dictionary<String,Any> = ["sww": 123,"frg":"911"] //写法二 let dict2 = ["sww": 123,"frg":"911"] as [String : Any] //写法三,常用写法 let dict1 : [String: Any] = ["sww": 123,"frg":"911"] print(dict1,dict2,dict3) //2.如何定义可变字典 //1> 定义可变字典:使用var修饰 //写法一 var dict4 = Dictionary<String,Any>() //写法二 var dicm5 = [String : Any]() print(dict4,dicm5) //2> 对可变字典添加元素 dict4["name"] = "why" //没有oc中的setonjectle dict4["age"] = 20 dict4["height"] = 1.88 //3》删除元素 dict4.removeValue(forKey:"name") //4> 修改元素 dict4["name"] = "lmj" dict4.updateValue("lmj",forKey: "name") //5>查找元素 //dicm["age"] //3.遍历 //遍历所有的values for value in dict4.values { print(value) } //遍历所有的key for key in dict4.keys { print(key) } //4.字典合并 var dict7 :[String:Any] = ["name":"why","age":10] let dict8 :[String:Any] = ["height":1.88,"phonenumber":"110"] //let result = dict1 + dict2 for (key,value) in dict8 { dict7[key] = value } print(dict7)原文链接:https://www.f2er.com/swift/321468.html