Jua*_*uan 7 generics dictionary swift
我试图找到一种很好的、干净的和通用的方式来扩展字典,这样我就可以将一个元素添加到存储在字典中的数组中,但不必显式检查该条目的键是否存在。
换句话说,让扩展程序进行密钥检查;如果存在,则将该元素添加到该键中包含的数组中,如果不存在,则通过存储包含该元素的新数组来创建该键。
我现在使用的代码如下:
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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认识到这可能有点牵强,但我发现编写这些有助于清理代码的扩展很有趣。我也开始考虑确定特定代码语法,然后弄清楚如何实现它的想法。对此有任何想法都非常受欢迎!
这是可能的解决方案。使用 Xcode 11.4 进行测试
extension Dictionary {
mutating func add<T>(_ element: T, toArrayOn key: Key) where Value == [T] {
self[key] == nil ? self[key] = [element] : self[key]?.append(element)
}
}
Run Code Online (Sandbox Code Playgroud)