Created
April 5, 2020 21:20
-
-
Save JacopoMangiavacchi/91aa02fb185e7516694b0f757da8a663 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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