Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created April 21, 2019 17:06
Show Gist options
  • Save natecook1000/8e45335ad31a37c0cfa55fd62ddf89e1 to your computer and use it in GitHub Desktop.
Save natecook1000/8e45335ad31a37c0cfa55fd62ddf89e1 to your computer and use it in GitHub Desktop.
public struct DefaultedDictionary<Key: Hashable, Value> {
var _data: [Key: Value]
var _default: Value
public init(default defaultValue: Value) {
_data = [:]
_default = defaultValue
}
public init(_ data: [Key: Value], default defaultValue: Value) {
_data = data
_default = defaultValue
}
public var count: Int {
return _data.count
}
public subscript(key: Key) -> Value {
get {
return _data[key] ?? _default
}
set {
_data[key] = newValue
}
}
public mutating func removeValue(forKey key: Key) -> Value {
return _data.removeValue(forKey: key) ?? _default
}
}
extension DefaultedDictionary: Collection {
public typealias Element = (key: Key, value: Value)
public typealias Index = Dictionary<Key, Value>.Index
public var startIndex: Index {
return _data.startIndex
}
public var endIndex: Index {
return _data.endIndex
}
public func index(after i: Index) -> Index {
return _data.index(after: i)
}
public subscript(i: Index) -> (key: Key, value: Value) {
return _data[i]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment