在swift中,key:key值一定是可hash的,一定是獨一無二的,swift的基本數據類型(String,Int,Float)都是可哈希的,所以都可以作為key值。 value:沒有要求
直接上代碼了,注釋給大家標的很明白
//創建字典並賦值
let dict = ["name":"xiaoyu","age":12]
let dict2:[String:Any] = ["name":"xiaoyu","age":12];
let dict3:Dictionary<String,Any> = ["name":"xiaoyu","age":13,"height":130]
print(dict3)
//創建空字典
let dict4:[String:Any] = [:]
let dict5:[String:Any] = Dictionary()
//創建可變字典
var dict6:[String:Any] = ["name":"xiaoyu"]
//更新字典的數據 value輸出的是原來的key對應的value值
if let Value = dict6.updateValue("dayu", forKey: "name")
{
print(Value)
print(dict6)
}
//刪除字典元素
dict6.removeValueForKey("name")
//刪除全部元素
dict6.removeAll()
dict6.removeAll(keepCapacity: true)
//遍歷字典
for (key,value) in dict6
{
print("key:\(key) value:\(value)")
}
for key in dict6.keys{
print("key:\(key)")
}
//合並字典
var dict7:[String:Any] = ["name":"小雨","age":133]
var newDict8:[String:Any] = ["weight":"小於","height":13]
for (key,value) in newDict8{
dict7.updateValue(value, forKey: key)
}
print("dict7:\(dict7)");