Created
January 21, 2017 20:50
-
-
Save gsabran/713a770a224f21638c12b25fd668c1b6 to your computer and use it in GitHub Desktop.
Revisions
-
gsabran created this gist
Jan 21, 2017 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,39 @@ class Weak<T: AnyObject> { weak var value : T? init (value: T) { self.value = value } } public class Model { let id: String private init(from payload: JSON) { ... } private static var instanciated = [String: Weak<Model>]() deinit { if Model.instanciated[id]?.value === self { Model.instanciated.removeValue(forKey: id) } } private static func getCacheOrCache(model: Model) -> Model { if let existingInstance = instanciated[model.id]?.value { update(cached: existingInstance, with: model) return existingInstance } instanciated[model.id] = Weak<Model>(value: model) return model } private static func update(cached instance: Model, with update: Model) { instance.someField = update.someField } static func create(from payload: JSON) Model { let model = Model(from: payload) return getCacheOrCache(model: model) } } // then instead of doing `let m = Model(…)`, you do `let m = Model.create(…)`