Swift中的字典类型是Dictionary,泛型集合。var修饰是可变字典,let修饰时可变字典
声明字典类型:
var dict1: Dictionaryvar dict2: [Int: String]
初始化:必须进行初始化才能使用
var dict1: Dictionary= Dictionary()
// 定义一个可变字典
var dict3 : [String : NSObject] = [String : NSObject]()
// 定义字典的同时进行初始化
let dict4 = ["name" : "xiaosan", "age" : 18]
// 类型推导出 [String : NSObject] 类型
// swift中任意对象,通常不使用NSObject,使用AnyObjectvar
dict5 : Dictionarydict5 = ["name" : "dd", "age" : 18]
字典的基本操作
// 字典的操作
var dict : [String : AnyObject] = [String : AnyObject]()
dict = ["age" : 18, "height" : 1.74, "name" : "xiaocan"]
// 添加数据
dict["weight"] = 60.0
// 删除数据
dict.removeValueForKey("age")
// 修改字典
dict["name"] = "xiaoer"
dict["age"] = 18 // 如果没有这个键,则为添加数据
// 查询
dict["name"]
字典的遍历
// 遍历字典中所有的值
for value in dict.values {
print(value)
}
// 遍历字典中所有的键
for key in dict.keys {
print(key)
}
// 遍历所有的键值对
for (key, value) in dict {
print(key)
print(value)
}
字典的合并
var myDict1 = ["name" : "xiaosan", "age" : 20]
var myDict2 = ["height" : 1.77, "address" : "taikang"]
// 字典不可以相加合并 另外类型不同也不能合并
for (key, value) in myDict1 {
myDict2[key] = value
}
removeValueForKey && updateValue(forKey:)
字典的updateValue(forKey:) 方法去设置或者更新一个特定键的值,如果键不存在则会设置它的值,如果键存在则会更新它的值, 和下标不一样是, updateValue(forKey:) 方法如果更新时,会返回原来旧的值rThis enables you to 可以使用这个来判断是否发生了更新。
var dict = ["name" : "siri", "age" : 18, "address" : "nanjing"]
iflet oldValue = dict.updateValue("Siri", forKey: "name") {
print(oldValue) // siri
}
//使用下标语法把他的值分配为nil,来移除这个键值对。
dict["age"] = nil
print(dict) // ["address": nanjing, "name": Siri]
使用removeValueForKey方法,如果存在键所对应的值,则移除一个键值对,并返回被移除的值,否则返回nil。
if let removedValue = dict.removeValueForKey("address") {
print("The remove dict's adddress is \(removedValue)") // The remove dict's adddress is nanjing
} else {
print("The dict does not contain a value for address")
}
参考:http://www.cnblogs.com/10-19-92/p/5627619.html