Skip to content

Instantly share code, notes, and snippets.

@aspitz
Created November 2, 2014 14:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspitz/6e1b7e7251a1dab282a9 to your computer and use it in GitHub Desktop.
Save aspitz/6e1b7e7251a1dab282a9 to your computer and use it in GitHub Desktop.
Swift implementation of a bidirectional dictionary
struct BidirectionalDictionary<KeyType:Hashable, ValueType:Hashable>{
var keyToValue = [KeyType:ValueType]()
var valueToKey = [ValueType:KeyType]()
subscript(key:KeyType) -> ValueType? {
get {
return self.keyToValue[key]
}
set {
self.keyToValue[key] = newValue
if let aValue = newValue {
self.valueToKey[aValue] = key
}
}
}
subscript(value:ValueType) -> KeyType? {
get {
return self.valueToKey[value]
}
set(key) {
self.valueToKey[value] = key
if let aKey = key {
self.keyToValue[aKey] = value
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment