Skip to content

Instantly share code, notes, and snippets.

@dduan
Last active May 16, 2016 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dduan/31ed39c4c98ecb88290f0743cb394c20 to your computer and use it in GitHub Desktop.
Save dduan/31ed39c4c98ecb88290f0743cb394c20 to your computer and use it in GitHub Desktop.
A handy Swift dictionary that returns a specified default value for non-existing keys.
public struct DefaultDictionary<Key : Hashable, Value>: CollectionType {
private var _storage: [Key: Value]
private var _defaultValue: () -> Value
public typealias Element = (Key, Value)
public typealias Index = DictionaryIndex<Key, Value>
public var startIndex: Index {
return _storage.startIndex
}
public var endIndex: Index {
return _storage.endIndex
}
public func generate() -> DictionaryGenerator<Key, Value> {
return _storage.generate()
}
public subscript (position: Index) -> Element {
return _storage[position]
}
public subscript (key: Key) -> Value {
get {
if let value = _storage[key] {
return value
} else {
return _defaultValue()
}
}
set {
_storage[key] = newValue
}
}
init(defaultValue: () -> Value) {
_storage = [:]
_defaultValue = defaultValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment