Swift字典
2019-03-13 本文已影响0人
iOS_July
- 字典的定义
//字典的定义
func demoDict1() -> () {
//OC使用{}
//Swift使用[]
//[key: value] -> [String : NSObject]
let dict = ["name" : "July", "sex" : "男"]
print(dict)
//字典数组
let array: [[String: AnyObject]] = [
["name" : "July" as AnyObject, "sex" : "男" as AnyObject],
["name" : "june" as AnyObject, "sex" : "女" as AnyObject]
]
print(array)
}
- 字典的增删改查
//字典的增删改查
func demoDict2() -> () {
var dict = ["name" : "July", "sex" : "男"]
//增
dict["tag"] = "coder"
//改 通过 key 取值,key 在字典中必须是唯一的
//如果 key 存在,就修改
dict["name"] = "june"
//删 通过 key 来删除
dict.removeValue(forKey: "sex")
//查 通过 key 来取值
print(dict["name"] ?? "姓名")
print(dict)
}
- 字典的遍历
//字典的遍历
func demoDict3() -> () {
let dict = ["name" : "July", "sex" : "男"]
//元组(key: String, value: NSObejct)
for e in dict {
print("\(e.key) \(e.value)")
}
print("------------")
//前面的是key,后边是value,名字可以随意取
for (key, value) in dict {
print("\(key) \(value)")
}
}
- 字典的合并
//字典的合并
func demoDict4() -> () {
var dict1 = ["name" : "July", "sex" : "男"]
var dict2 = ["name" : "june", "sex" : "女", "age" : "20"]
//将dict2合并到dict1
//dict1 += dict2 //字典不能再像数组一样
//如果key 存在,会修改
//如果key 不存在,会新增
for e in dict2 {
dict1[e.key] = dict2[e.key]
}
}