samedi 3 septembre 2016

Enforce model unicity - Swift solution?

What is a good approach to ensure that a model representing an element identified by an id doesn't get instantiated twice? Are there some good libraries to do that in Swift? I could not find anything even though I suspect this to be a common problem.

I'd like something like this to happen:

let a = fetchElementWithId(123)
let b = fetchElementWithId(123)
// then a === b 

I thought of doing something like

class Weak<T: AnyObject> {
  weak var value : T?
  init(value: T) {
    self.value = value
  }
}

class Foo {
  private static var cache = [String: Weak<Foo>]()

  var id: String
  var bar: String

  static func initialize(id: String, bar: String) -> Foo {
    if let weakExistingModel = Foo.cache[id], let existingModel = weakExistingModel.value {
      existingModel.bar = bar
      return existingModel
    }
    return Foo(id: id, bar: bar)
  }

  private init(id: String, bar: String) {
    self.id = id
    self.bar = bar
    Foo.cache[id] = Weak(value: self)
  }
  deinit() {
    Foo.removeValueForKey(id)
  }
}

And then call the static initializer instead of the normal one. But things can get messy if I start to get subclasses that represent the same document etc.

So before I dig into this, I'm wondering what smart people have done about it before! I guess the solution is not particularly swift related (even though for instance in swift you can't override static functions, which could be an issue), but since I'm using swift I'm more interested in a libraries in that language.

Aucun commentaire:

Enregistrer un commentaire