我已经习惯使用Python的默认模式的模式是一个字典,如果没有明确设置给定键的值,则返回默认值.试图在Swift中这样做有点冗长.
var dict = Dictionary<String, Array<Int>>()
let key = "foo"
var value: Array<Int>! = dict[key]
if value == nil {
value = Array<Int>()
dict[key] = value
}
Run Code Online (Sandbox Code Playgroud)
我意识到我可以创建一个这样做的类,但是实际的Dictionary必须通过属性访问才能使用任何其他正常的Dictionary方法
class DefaultDictionary<A: Hashable, B> {
let defaultFunc: () -> B
var dict = Dictionary<A, B>()
init(defaultFunc: () -> B) {
self.defaultFunc = defaultFunc
}
subscript(key: A) -> B {
get {
var value: B! = dict[key]
if value == nil {
value = defaultFunc()
dict[key] = value
}
return value
}
set …Run Code Online (Sandbox Code Playgroud)