gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:18:22 25 4
gpt4 key购买 nike

在 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-使下游代码更简单希望也能最大限度地减少对单独 View 的需求。

最佳答案

尚不清楚其他代码,但前提是我会使用泛型,例如

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

}

关于swift - 使用 Swift 重构/组合多个几乎相同的类的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66820712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com