Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
final class Container<Key: Hashable & RawRepresentable> {
private var storage = [Key: [ContainerItem]]() {
didSet {
didChange()
}
}
init(content: [Key: [ContainerItem]] = [:]) {
storage = content
}
func add(_ item: ContainerItem, key: Key) {
if var current = storage[key] {
current.append(item)
storage[key] = current
}
else {
storage[key] = [item]
}
}
func items<T: ContainerItem>(forKey key: Key) -> [T] {
guard let all = storage[key] else { return [] }
return all as! [T]
}
var didChange: () -> Void = {}
}
protocol ContainerItem {
init?(jsonData: Data)
var jsonDataRepresentation: Data { get }
}
extension ContainerItem where Self: Codable {
init?(jsonData: Data) {
guard let object = try? JSONDecoder().decode(Self.self, from: jsonData) else { return nil }
self = object
}
var jsonDataRepresentation: Data {
return try! JSONEncoder().encode(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment