Created
December 28, 2015 00:48
-
-
Save Evertt/60cbb279bc8d83479b32 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
import Foundation | |
public struct OrderedDictionary<Tk: Hashable, Tv> : MutableCollectionType { | |
var keys: Array<Tk> = [] | |
var values: Dictionary<Tk,Tv> = [:] | |
public typealias Index = Int | |
public var count: Int { | |
return self.keys.count; | |
} | |
public var startIndex: Int { | |
return self.keys.startIndex | |
} | |
public var endIndex: Int { | |
return self.keys.endIndex | |
} | |
public init() {} | |
public func generate() -> AnyGenerator<(Tk, Tv)> { | |
var index = 0 | |
return anyGenerator { | |
if index < self.keys.count { | |
let key = self.keys[index] | |
let value = self.values[key]! | |
index += 1 | |
return (key, value) | |
} | |
return nil | |
} | |
} | |
public subscript(index: Int) -> (Tk, Tv)? { | |
get { | |
let key = self.keys[index] | |
return (key, self.values[key]!) | |
} | |
set(newValue) { | |
let key = self.keys[index] | |
self.values.removeValueForKey(key) | |
if let value = newValue { | |
self.keys[index] = value.0 | |
self.values[value.0] = value.1 | |
} else { | |
self.keys.removeAtIndex(index) | |
} | |
} | |
} | |
public subscript(key: Tk) -> Tv? { | |
get { | |
return self.values[key] | |
} | |
set(newValue) { | |
if newValue == nil { | |
self.values.removeValueForKey(key) | |
self.keys = self.keys.filter {$0 != key} | |
} | |
let oldValue = self.values.updateValue(newValue!, forKey: key) | |
if oldValue == nil { | |
self.keys.append(key) | |
} | |
} | |
} | |
public var description: String { | |
var result = "{\n" | |
for i in 0..<self.count { | |
result += "[\(i)]: \(self.keys[i]) => \(self[i])\n" | |
} | |
result += "}" | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment