Last active
October 19, 2019 05:52
-
-
Save laevandus/1e3e089b0c85b1527e3f7b4790fc3540 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
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