Swift對字典的常用基本使用

字典操作

//創建字典
var dict : Dictionary = ["111":"aaa","22":"bb","ccc":"333"]
//字典添加或更新元素
dict.updateValue("chaofan", forKey: "333")
dict["333"] = "我是3"
dict["444"] = "ddd"

//移除對象
dict.removeValueForKey("22")
dict["333"] = nil

//移除字典所有的對象
dict.removeAll()


//創建不可變字典
let mutableDict :NSMutableDictionary = ["111":"aaa","22":"bb"]

//更改value
mutableDict["111"] = "chaofan"

//添加元素
mutableDict.setValue("ccc", forKeyPath: "333")

//刪除元素
mutableDict.removeObjectForKey("22")

//取出元素
let value = mutableDict["111"]
print(value)

//字典總個數
print(mutableDict.count)



//字典遍歷
for key in dict{
    print(key)
}

for (key,value) in dict{
    print("key is \(key) and value is \(value)")
}

for (key, _) in dict {
    print(key)
}  

for (_, value) in dict {  
    print(value)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章