Skip to content

Instantly share code, notes, and snippets.

@JacopoMangiavacchi
Created April 5, 2020 21:20
Show Gist options
  • Save JacopoMangiavacchi/91aa02fb185e7516694b0f757da8a663 to your computer and use it in GitHub Desktop.
Save JacopoMangiavacchi/91aa02fb185e7516694b0f757da8a663 to your computer and use it in GitHub Desktop.
import Foundation
struct OrderedDict<K: Hashable, V> {
var _dict = [K : V]()
var _ordered = [K]()
var keys: [K] {
_ordered
}
subscript(index: K) -> V? {
get {
_dict[index]
}
set(newValue) {
if let _ = newValue {
if _ordered.firstIndex(of: index) == nil {
_ordered.append(index)
}
}
else {
if let firstIndex = _ordered.firstIndex(of: index) {
_ordered.remove(at: firstIndex)
}
}
_dict[index] = newValue
}
}
}
var dict = OrderedDict<String, Int>()
dict["one"] = 1
dict["two"] = 2
dict["three"] = 3
dict["four"] = 4
dict["five"] = 5
dict["three"] = nil
dict["three"] = 3
print(dict.keys)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment