Created
June 21, 2015 22:34
-
-
Save oisdk/db9e603d64db47db842a to your computer and use it in GitHub Desktop.
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
public struct OrderedDict<K : Hashable, T> : | |
CollectionType, | |
DictionaryLiteralConvertible, | |
CustomStringConvertible { | |
private var keys: [K] | |
private var vals: [K : T] | |
public var endIndex: Int { return keys.endIndex } | |
public var startIndex: Int { return 0 } | |
public subscript (i: Int) -> (K, T) { | |
get { | |
return (keys[i], vals[keys[i]]!) | |
} set(from) { | |
self.vals[from.0] = from.1 | |
self.keys.append(from.0) | |
} | |
} | |
public subscript (key: K) -> T? { | |
get { | |
return self.vals[key] | |
} set(from) { | |
self.vals[key] = from | |
self.keys.append(key) | |
} | |
} | |
public init(dictionaryLiteral elements: (K, T)...) { | |
self.keys = elements.map { $0.0 } | |
self.vals = Dictionary<K, T>() | |
for (key, value) in elements { self.vals[key] = value } | |
} | |
public func generate() -> IndexingGenerator<Array<(K, T)>> { | |
return self.keys.map { ($0, vals[$0]!) }.generate() | |
} | |
public var description: String { | |
return ", ".join(self.keys.map {"[\($0):\(vals[$0]!)]"}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment