Last active
May 16, 2016 22:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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