[Model] Store and retrieve entities by type
jsbean opened this issue · comments
James Bean commented
A little bit of a work around needs to be made In order to keep the model type-safe:
extension Model {
var entitiesByType: [String: [Identifier]] = [:]
func store <T> (_ value: T, ...) -> Identifier {
let identifier = // make new identifier
entitiesByType.safelyAppend(value, forKey: "\(T.self)")
return identifier
}
func retrieve <T> (_ identifier: Identifier) -> T {
return entities["\(T.self)"] as! [T]
}
}
James Bean commented
The currently solution uses the String
key. This is problematic for two reasons: with thousands or millions of hits, the creation of strings for the types is quite expensive. Furthermore, this doesn't actually preserve type information.
Instead, it may be better to implement Model
as a protocol. Concrete implementations of Model
-conforming types could extend the specific types they can store while retaining type information.