swift基本資料型別使用-字典使用
阿新 • • 發佈:2020-09-15
目錄
1.定義的定義
1> 不可變字典: let
2> 可變字典: var
2.對可變字典的基本操作
增刪改查
3.遍歷字典
1> 所有的key
2> 所有的value
3> 所有的key/value
4.字典合併
5.示例
// 1.如何定義字典 // 1> 定義不可變字典 : 使用let修飾 let a : Int = 10 // 編譯器會根據[]中是一個個元素(陣列),還是鍵值對(字典) //let dict = ["name" : "why", "age" : 18, "height" : 1.88] as [String : Any] //let dict = ["123" : "321", "abc" : "cba"] 不需要進行轉化 // Array<String> --> [String] // let dict : Dictionary<String, Any> = ["name" : "why", "age" : 18, "height" : 1.88] // dict["phoneNum"] = "+86 110" 錯誤寫法 let dict : [String : Any] = ["name" : "why", "age" : 18, "height" : 1.88] // 2> 定義可變字典 : 使用var修飾 // var arrayM = [String]() // var dictM = Dictionary<String, Any>() var dictM = [String : Any]() // 2.對可變字典的基本操作(增刪改查) // 2.1.新增元素 dictM["name"] = "why" dictM["age"] = 18 dictM["height"] = 1.88 dictM // 2.2.刪除元素 dictM.removeValue(forKey: "height") dictM // 2.3.修改元素 dictM["name"] = "lmj" dictM.updateValue("lnj", forKey: "name") dictM // 2.4.查詢元素 dictM["age"] // 3.遍歷字典 // 3.1.遍歷字典中所有的key for key in dict.keys { print(key) } print("---------") // 3.2.遍歷字典中所有的value for value in dict.values { print(value) } print("---------") // 3.3.遍歷字典中所有的key/value for (key, value) in dict { print(key, value) } // 4.字典合併 var dict1 : [String : Any] = ["name" : "why", "age" : 18] let dict2 : [String : Any] = ["height" : 1.88, "phoneNum" : "+86 110"] //let resultDict = dict1 + dict2 for (key, value) in dict2 { dict1[key] = value }