Created
July 13, 2020 21:00
-
-
Save ricardopsantos/d53dd844e953783734d933103c6b24c4 to your computer and use it in GitHub Desktop.
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
//: A UIKit based Playground for presenting user interface | |
import UIKit | |
import Foundation | |
struct SortedDic: Sequence, IteratorProtocol { | |
public init() { } | |
public init(order: [String], dic: [String:Int]) { | |
self.order = order | |
self.dic = dic | |
} | |
private var index = 0 | |
private var dic: [String:Int] = [:] | |
private var order: [String] = [] | |
func makeIterator() -> SortedDic { | |
return SortedDic(order: order, dic: dic) | |
} | |
mutating func next() -> (String, Int)? { | |
guard index < order.count else { return nil } | |
let key = order[index] | |
guard let value = dic[key] else { return nil } | |
index += 1 | |
return (key, value) | |
} | |
subscript(key: String) -> Int? { | |
get { | |
return dic[key] | |
} | |
set(newValue) { | |
dic[key] = newValue | |
if newValue != nil { | |
order.append(key) | |
} else { | |
order = order.filter({ $0 != key }) | |
} | |
} | |
} | |
} | |
var dic = SortedDic() | |
dic["A"] = 1 | |
dic["B"] = 2 | |
dic["C"] = 3 | |
dic["B"] = nil | |
dic.forEach { (some) in | |
print(some) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment