Skip to content

Instantly share code, notes, and snippets.

@fwhenin
Created December 18, 2014 20:23
Show Gist options
  • Save fwhenin/0c8457a0ff29a570b5b7 to your computer and use it in GitHub Desktop.
Save fwhenin/0c8457a0ff29a570b5b7 to your computer and use it in GitHub Desktop.
Swift Ordered Dictionary
//
// 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]!);
}
}
@blixt
Copy link

blixt commented Aug 19, 2015

@mattdipasquale Then how would you get the value for a specific key (orderedDict["something"])?

@Qata
Copy link

Qata commented Feb 8, 2017

@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