Skip to content

Instantly share code, notes, and snippets.

@fwhenin
Created December 18, 2014 20:23
Show Gist options
  • Select an option

  • Save fwhenin/0c8457a0ff29a570b5b7 to your computer and use it in GitHub Desktop.

Select an option

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]!);
}
}
@dsharmaradicle

Copy link
Copy Markdown

Any example to use into Swift?

@ma11hew28

Copy link
Copy Markdown

Why not just use an Array of tuples instead of an OrderedDictionary?

@blixt

blixt commented Aug 19, 2015

Copy link
Copy Markdown

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

@Qata

Qata commented Feb 8, 2017

Copy link
Copy Markdown

@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