在 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-希望也使下游代码更简单尽量减少对单独视图的需要。
其他代码不清楚,但对于那些我会使用泛型,比如
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)
| 归档时间: |
|
| 查看次数: |
44 次 |
| 最近记录: |