使用Swift重构/组合多个几乎相同的类的推荐方法?

在 Swift 中,我如何将以下内容组合成一个类?

class FirstClass: Codable, ObservableObject {
  @Published var int: Int
  @Published var bool: Bool
  @Published var firstObject: FirstType

// plus inits and custom decoding/encoding stuff

}

class SecondClass: Codable, ObservableObject {
  @Published var int: Int
  @Published var bool: Bool
  @Published var secondObject: SecondType

// plus inits and custom decoding/encoding stuff

}

class ThirdClass: Codable, ObservableObject {
  @Published var int: Int
  @Published var bool: Bool
  @Published var thirdObject: ThirdType

// plus inits and custom decoding/encoding stuff

}

(with FirstType, SecondType and ThirdType also being class models that conform to Codable and ObservableObject)

为了结束这样的事情:

class CommonClass: Codable, ObservableObject {
  @Published var int: Int
  @Published var bool: Bool
  @Published var object: CommonType // which could accept FirstType, SecondType or ThirdType

// plus inits and custom decoding/encoding stuff

}

我该怎么做呢?是否有更好的方法仍然按我的意图工作?

我基本上是想实现两件事:1-避免重复代码(就像在我的现实生活中一样,除了 int 和 bool 之外,还有更多的共同变量)和 2-希望也使下游代码更简单尽量减少对单独视图的需要。

回答

其他代码不清楚,但对于那些我会使用泛型,比如

class CommonClass<T>: Codable, ObservableObject {
//class CommonClass<T: CommonType>: Codable, ObservableObject { // << as variant
  @Published var int: Int
  @Published var bool: Bool
  @Published var object: T

// plus inits and custom decoding/encoding stuff

}

  • One could also do it with a protocol + extension, but I think the generic approach is probably the best solution in this case with the least code duplication/boilerplate.

以上是使用Swift重构/组合多个几乎相同的类的推荐方法?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>