【发布时间】:2020-06-18 09:09:34
【问题描述】:
我正在尝试找到一种很好、干净且通用的方法来扩展字典,以便我可以将元素添加到存储在字典中的数组中,而无需显式检查该条目的键是否存在。
换句话说,让扩展来做密钥检查;如果确实存在,则将该元素添加到包含在该键中的数组中,如果它不存在,则通过使用该元素存储一个新数组来创建该键。
我现在使用的代码是这样的:
dictionary[key] == nil ? dictionary[key] = [element] : dictionary[key]?.append(element)
但我很想写这样的东西:
dictionary.add(element, toArrayOn: key)
扩展看起来像这样:
extension Dictionary {
mutating func add(element: SomeElement, toArrayOn key: Key) {
// Check if self[key] exisists:
// If self[key] != nil, check if the value is Array<SomeElement>, if so append the element to the Array, if not throw an error.
// If self[key] == nil, make an empty Array<SomeElement> and insert the element.
}
}
}
我知道这可能有点牵强,但我发现编写这类有助于清理代码的扩展很有趣。我也开始接受决定特定代码语法然后弄清楚如何实现它的想法。 非常欢迎对此提出任何想法!
【问题讨论】:
-
这个已经存在,你可以使用
default追加,比如dictionary[key, default: []].append(element),如果字典中不存在该键,则创建一个新的空数组
标签: swift dictionary generics