Dictionary
- 1: 创建
可以通过序列或者包含元祖的数组去创建dic
let sque = zip(97..., ["a", "b", "c", "d", "e", "f"])
var dic = Dictionary(uniqueKeysWithValues: sque)
print(dic)
//[100: "d", 101: "e", 99: "c", 97: "a", 98: "b", 102: "f"]
let arr = Array(sque)
print(arr)
//[(97, "a"), (98, "b"), (99, "c"), (100, "d"), (101, "e"), (102, "f")]
dic = Dictionary(uniqueKeysWithValues: arr)
print(dic)
//[100: "d", 101: "e", 99: "c", 97: "a", 98: "b", 102: "f"]
- 2:通过元祖数组创建dic并且过滤掉重复的键名
let arr = [("a", 2), ("b", 3), ("b", 4), ("a", 4)]
var dic = Dictionary.init(arr) { (first, _) in
first
}
print(dic)
//["b": 3, "a": 2]
dic = Dictionary(arr) { (_, last) in
last
}
print(dic)
//["b": 4, "a": 4]
- 3:还可以做很多其他的操作,通过元祖序列,合并相同的键名,生成新的字典
let sortingHat = [
("a", "1"), ("b", "2"),
("c", "4"), ("d", "3"), ("e", "5"), ("a", "6"),
("a", "7"), ("b", "8"),
("c", "9"), ("f", "10")
]
let houses = Dictionary(
sortingHat.map { ($0.0, [$0.1]) },
uniquingKeysWith: { (current, new) in
return current + new
})
print(houses)
//["b": ["2", "8"], "a": ["1", "6", "7"], "c": ["4", "9"], "e": ["5"], "f": ["10"], "d": ["3"]]
计算字符的个数
let str = "Sometimes affection is a shy flower that takes time to blossom."
var frequencies: [Character: Int] = [:]
let baseCounts = zip(
str.filter { $0 != " " }.map { $0 },
repeatElement(1, count: Int.max))
frequencies = Dictionary(baseCounts, uniquingKeysWith: +)
print(frequencies)
//["w": 1, "n": 1, ".": 1, "o": 6, "f": 3, "k": 1, "t": 7, "S": 1, "b": 1, "a": 4, "i": 4, "r": 1, "m": 4, "c": 1, "e": 6, "s": 6, "l": 2, "y": 1, "h": 2]
还有很多高级的用法,大家可以去查下资料
- 4:给键名访问提供默认值
在以前我们通过key获得Value时会获得一个optional类型的值,因为在字典中可能不存在这个键对应的值,如果要用的时候我们需要解包,而在Swift4中可以通过另外的方式添加默认值
let dic = ["a": 1, "b": 2, "c": 3]
var swift3 = dic["a"] 或者
swift3 = dic["a"] ?? 0
var swift4 = dic["a", default: 0]
上面的例子可以通过如下的代码实现
let str = "Sometimes affection is a shy flower that takes time to blossom."
var frequencies: [Character: Int] = [:]
let newStr = str.filter { $0 != " "}
newStr.map {
return frequencies[$0, default:0] += 1
}
print(frequencies)
//结果同上
- 5:创建分组字典,可以根据提供的关键词,创建一个分组后的字典
let names = ["Harry", "ron", "Hermione", "Hannah", "neville", "pansy", "Padma"].map { $0.capitalized }
let nameList = Dictionary(grouping: names) { $0.first!}
print(nameList)
//["H": ["Harry", "Hermione", "Hannah"], "R": ["Ron"], "N": ["Neville"], "P": ["Pansy", "Padma"]]
网友评论