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

Rib*_*ena 2 swift swiftui

在 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)

Run Code Online (Sandbox Code Playgroud)

为了结束这样的事情:

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

Asp*_*eri 5

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

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

}
Run Code Online (Sandbox Code Playgroud)

  • 人们也可以使用协议+扩展来做到这一点,但我认为通用方法可能是这种情况下最好的解决方案,具有最少的代码重复/样板。 (2认同)