lundi 29 juin 2020

Implement Decorator Pattern with generics in Swift

I am new to Swift, but I have plenty of experience in other languages like Java, Kotlin, Javascript, etc. It's possible that what I want to do is not supported by the language, and I've pored over the Swift Language Guide looking for the answer.

I want to implement the decorator pattern, using generics. I easily did this in Kotlin, and I'm porting the library to Swift.

class Result<T> {
  let result: T?
  let error: NSError?

  init(result: T?, error: NSError?) {
    self.result = result
    self.error = error
  }
}

protocol DoSomething {
  associatedtype T

  func doSomething() -> Result<T>
}

protocol StoreSomething {
  associatedtype T

  func storeSomething(thing: Result<T>)
}

/*
 * DOES NOT COMPILE
 */
class StoringSomething<T> {
  private let delegate: DoSomething
  private let storage: StoreSomething

  func doSomething() -> Result<T> {
    let result = delegate.doSomething()

    storage.storeSomething(thing: result)

    return result
  }
}

I get a Protocol 'DoSomething' can only be used as a generic constraint because it has Self or associated type requirements error from the compiler. I've tried using a typealias and other ideas from SO and the Swift manual.

Aucun commentaire:

Enregistrer un commentaire