Last active
August 25, 2021 07:58
-
-
Save CanTheAlmighty/70b3bf66eb1f2a5cee28 to your computer and use it in GitHub Desktop.
Two-Way Dictionary in Swift
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
struct DictionaryTwoWay<S:Hashable,T:Hashable> : DictionaryLiteralConvertible | |
{ | |
// Literal convertible | |
typealias Key = S | |
typealias Value = T | |
// Real storage | |
private var st : [S : T] = [:] | |
private var ts : [T : S] = [:] | |
init(leftRight st : [S:T]) | |
{ | |
var ts : [T:S] = [:] | |
for (key,value) in st | |
{ | |
ts[value] = key | |
} | |
self.st = st | |
self.ts = ts | |
} | |
init(rightLeft ts : [T:S]) | |
{ | |
var st : [S:T] = [:] | |
for (key,value) in ts | |
{ | |
st[value] = key | |
} | |
self.st = st | |
self.ts = ts | |
} | |
init(dictionaryLiteral elements: (Key, Value)...) | |
{ | |
for element in elements | |
{ | |
st[element.0] = element.1 | |
ts[element.1] = element.0 | |
} | |
} | |
init() { } | |
subscript(key : S) -> T? | |
{ | |
get | |
{ | |
return st[key] | |
} | |
set(val) | |
{ | |
if let val = val | |
{ | |
st[key] = val | |
ts[val] = key | |
} | |
} | |
} | |
subscript(key : T) -> S? | |
{ | |
get | |
{ | |
return ts[key] | |
} | |
set(val) | |
{ | |
if let val = val | |
{ | |
ts[key] = val | |
st[val] = key | |
} | |
} | |
} | |
} | |
// Example usage, starting from Dictionary Literal | |
let dict : DictionaryTwoWay<String, Int> = ["Hello" : 3] | |
dict[3] // Prints "Hello" | |
dict["Hello"] // Prints 3 | |
// Start with initializer | |
let dict2 : DictionaryTwoWay<String, Int>(leftRight: ["World" : 10]) | |
// Start with backwards initializer | |
let dict3 : DictionaryTwoWay<Int, String>(rightLeft: [10 : "World"]) |
By the way, it's not suitable to suppose S and T are different types.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does NOT compile now.