Created
December 18, 2014 20:23
-
-
Save fwhenin/0c8457a0ff29a570b5b7 to your computer and use it in GitHub Desktop.
Swift Ordered Dictionary
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
// | |
// OrderedDictionary.swift | |
// DMS | |
// | |
// Created by Freddy on 12/12/14. | |
// Copyright (c) 2014 DMSCompany. All rights reserved. | |
// | |
import Foundation | |
struct OrderedDictionary<Tk: Hashable, Tv>{ | |
var keys: Array<Tk> = [] | |
var values: Dictionary<Tk,Tv> = [:] | |
init(){ | |
} | |
subscript(key:Tk) -> Tv?{ | |
get{ | |
return self.values[key]; | |
} | |
set(newValue){ | |
if (newValue == nil){ | |
self.values.removeValueForKey(key) | |
self.keys.filter {$0 != key} | |
return; | |
} | |
let oldValue = self.values.updateValue(newValue!, forKey: key); | |
if oldValue == nil{ | |
self.keys.append(key); | |
} | |
} | |
} | |
func getPair(i: Int) -> (key: Tk, value: Tv)?{ | |
var key = self.keys[i]; | |
return (key, self.values[key]!); | |
} | |
} |
@mattdipasquale I've done that in my own projects but it causes O(n) lookup times which can be easily avoided by using an actual dictionary.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mattdipasquale Then how would you get the value for a specific key (
orderedDict["something"]
)?