|
| 1 | +// |
| 2 | +// OrderedDictionary.swift |
| 3 | +// URLNavigator |
| 4 | +// |
| 5 | +// Created by Jerome Pasquier on 28/01/2019. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +struct OrderedDictionary<Key: Hashable, Value> { |
| 11 | + var keys = [Key]() |
| 12 | + var values = [Key: Value]() |
| 13 | + |
| 14 | + var count: Int { |
| 15 | + return self.keys.count |
| 16 | + } |
| 17 | + |
| 18 | + subscript(index: Int) -> Value? { |
| 19 | + get { |
| 20 | + let key = self.keys[index] |
| 21 | + return self.values[key] |
| 22 | + } |
| 23 | + set(newValue) { |
| 24 | + let key = self.keys[index] |
| 25 | + if newValue != nil { |
| 26 | + self.values[key] = newValue |
| 27 | + } else { |
| 28 | + self.values.removeValue(forKey: key) |
| 29 | + self.keys.remove(at: index) |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + subscript(key: Key) -> Value? { |
| 35 | + get { |
| 36 | + return self.values[key] |
| 37 | + } |
| 38 | + set(newValue) { |
| 39 | + if let newVal = newValue { |
| 40 | + let oldValue = self.values.updateValue(newVal, forKey: key) |
| 41 | + if oldValue == nil { |
| 42 | + self.keys.append(key) |
| 43 | + } |
| 44 | + } else { |
| 45 | + self.values.removeValue(forKey: key) |
| 46 | + self.keys = self.keys.filter {$0 != key} |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | +} |
| 52 | + |
| 53 | +extension OrderedDictionary: CustomStringConvertible { |
| 54 | + var description: String { |
| 55 | + let isString = type(of: self.keys[0]) == String.self |
| 56 | + var result = "[" |
| 57 | + for key in keys { |
| 58 | + result += isString ? "\"\(key)\"" : "\(key)" |
| 59 | + result += ": \(self[key]!), " |
| 60 | + } |
| 61 | + result = String(result.dropLast(2)) |
| 62 | + result += "]" |
| 63 | + return result |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +extension OrderedDictionary: Sequence { |
| 68 | + func makeIterator() -> AnyIterator<Value> { |
| 69 | + var counter = 0 |
| 70 | + return AnyIterator { |
| 71 | + guard counter<self.keys.count else { |
| 72 | + return nil |
| 73 | + } |
| 74 | + let next = self.values[self.keys[counter]] |
| 75 | + counter += 1 |
| 76 | + return next |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments