// 不可变字典
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]
网友评论