Skip to content

Instantly share code, notes, and snippets.

@ericcgu
Created October 8, 2014 01:21
Show Gist options
  • Save ericcgu/0352fff45582552686d5 to your computer and use it in GitHub Desktop.
Save ericcgu/0352fff45582552686d5 to your computer and use it in GitHub Desktop.
import UIKit
struct OrderedDictionary<Tk: Hashable, Tv> {
var keys: Array<Tk>
var values: Dictionary<Tk,Tv>
// 1
mutating func insert(value: Tv, forKey key: Tk, atIndex index: Int) -> Tv?
{
var adjustedIndex = index
// 2
let existingValue = self.values[key]
if existingValue != nil {
// 3
let existingIndex = find(self.keys, key)!
// 4
if existingIndex < index {
adjustedIndex--
}
self.keys.removeAtIndex(existingIndex)
}
// 5
self.keys.insert(key, atIndex:adjustedIndex)
self.values[key] = value
// 6
return existingValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment