// 不可变字典
let keepDictionary = ["time": 20210811, "age": 18, "height": 182]
print(keepDictionary) // ["height": 182, "time": 20210811, "age": 18]
for (key, value) in keepDictionary {
print(key, value)
}
// 替换字典元素 - 生成新字典
let keepDictionary2 = keepDictionary.map { (key: String, value: Int) in
return 123
}
print(keepDictionary2) // [123, 123, 123]
// 筛选字典 - 生成新字典
let keepDictionary3 = keepDictionary.filter { element in
return element.value > 18
}
print(keepDictionary3) // ["time": 20210811, "height": 182]
// 字典排序 - 生成新数组 数组元素是元组
let keepDictionary4 = keepDictionary.sorted { el1, el2 in
return el1.value > el2.value
}
print(keepDictionary4) // [(key: "time", value: 20210811), (key: "height", value: 182), (key: "age", value: 18)]
print("-------------------")
//
print(keepDictionary.first ?? 0) // (key: "height", value: 182) 结果随机
print(keepDictionary.startIndex) // 注意这个不是int类型,与Array不同
print(keepDictionary.endIndex) // 注意这个不是int类型,与Array不同
print(keepDictionary.count) // 3
print("-------------------")
// 可变字典
// var mutableDictionary = [String: Int]()
var mutableDictionary = ["time": 1, "age2": 2, "height3": 3]
// 字典合并
mutableDictionary.merge(keepDictionary) { mutableDictionaryElementValue, keepDictionaryElementValue in
print(mutableDictionaryElementValue, keepDictionaryElementValue) // 1 20210811
return mutableDictionaryElementValue // 如果key重复 则会在闭包中进行取舍
}
// CURD字典元素
mutableDictionary["width"] = 130 // 增改
mutableDictionary.removeValue(forKey: "age") // 删
mutableDictionary["width"] = 567 // 增改
mutableDictionary.updateValue(12306, forKey: "火车票") // 增改
print(mutableDictionary["width"] ?? 0) // 查 567
print(mutableDictionary) // ["height3": 3, "height": 182, "width": 567, "time": 1, "火车票": 12306, "age2": 2]
print(mutableDictionary.isEmpty) // 判断是否为空
//如果想在字典中放置不同类型的value,则使用
var anyDictionary = [String: Any]()
anyDictionary["name"] = "baidu"
anyDictionary["age"] = 18
anyDictionary["height"] = 182.2
anyDictionary["pet"] = Dog()
print(anyDictionary) // ["age": 18, "pet": swift_clt.Dog, "name": "baidu", "height": 182.2]
Swift字典
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1、JSONString转换为字典 /// JSONString转换为字典 ////// - Paramete...
- func toJSONString(dict:NSDictionary?)->String{ let data =...