Skip to content

Instantly share code, notes, and snippets.

@CanTheAlmighty
Last active August 25, 2021 07:58
Show Gist options
  • Save CanTheAlmighty/70b3bf66eb1f2a5cee28 to your computer and use it in GitHub Desktop.
Save CanTheAlmighty/70b3bf66eb1f2a5cee28 to your computer and use it in GitHub Desktop.
Two-Way Dictionary in Swift
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"])
@amomchilov
Copy link

Assigning nil should delete key/value pairs, not be a no-op.

@acalism
Copy link

acalism commented Aug 25, 2021

Does NOT compile now.

@acalism
Copy link

acalism commented Aug 25, 2021

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