1、字典的定义
//OC 定义字典使用{}
//Swift 中使用[]
//[KEY:VALUE]->[String:NSObject]
let dict = ["name":"张","age":10]
print(dict)
//定义字典的数组 - 提示,这种格式在开发中使用最多
/**
An object that may be converted to JSON must have the following properties:
所有对象能被转换成 JSON(字典或者数组) 必须遵循以下规则
- Top level object is an NSArray or NSDictionary
- 定义节点时数组/字典
- All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
- 所有对象必须是NSString ,NSNumber,NSArray, NSDictionary, or NSNull
- NSArray, NSDictionary可以被嵌套使用
- All dictionary keys are NSStrings
所有的key都是NSStrings
- NSNumbers are not NaN or infinity
- NSNumbers不为空或者无穷大
*/
let array: [[String:NSObject]] = [
["name":"张","age":10],
["name":"li","age":100],
]
2、增删改
//可变var 不可变let
var dict = ["name":"张","age":10]
//新增 - 如果key不存在就是新增
dict["title"] = "打个"
//修改 - 如果key存在就是修改
dict["name"] = "大西瓜"
print(dict)
//删除 - 直接给定KEY
//***字典是通过KEY 来定位值的,KEY 必须是可以’hash‘哈希的 MD5一样
//hsah 就是将字符串变成唯一的‘整数’,便于查找,提高字典遍历的速度
dict.removeValueForKey("age")
print(dict)
3、遍历
let dict = ["name":"张","age":10,"titile":"老板"]
//元组 [String : NSObject]
for e in dict {
print("(e.0)(e.1)")
}
for (key, value)in dict{
print("(key)(value)")
}
4、合并
var dict = ["name":"张","age":10,"titile":"老板"]
let dict1 = ["name":"大褂","age":100]
//合并
//字典不能直接相加
//思路:遍历dict1 一次设置
for e in dict1 {
dict[e.0] = dict1[e.0]
}