我想做这样的事情:
class Config<T> {
func configure(x:T)
// constraint B to be subclass of A
class func apply<A,B:A>(c:Config<A>, to:B) {
c.configure(to)
}
}
所以稍后,例如,我可以将 Config 应用于 UILabel:
class RedViewConfig<T:UIView> : Config<T> {
func configure(x:T) {
x.backgroundColor = .redColor();
}
}
let label = UILabel()
Config.apply(RedViewConfig(), to:label)
或者扩展配置类:
class RedLabelConfig<T:UILabel> : RedViewConfig<T> {
func configure(x:T) {
super.configure(x)
x.textColor = .redColor();
}
}
Config.apply(RedLabelConfig(), to:label)
我尝试这样做,但无法约束类。因此,我尝试使用协议(protocol)和关联类型,但是在子类化时,我在覆盖关联类型时发现了问题 ( like this)。
最佳答案
你真的需要通用参数B
吗?如果您的参数 to:
也被键入为 A
,则它可以是 A
的任何子类型。像这样:
class View {}
class LabelView : View {}
class Config<T> {
func configure(x:T) { print ("Configured: \(x)") }
}
func applyConfig<A> (c:Config<A>, to:A) {
c.configure(to)
}
applyConfig(Config<View>(), to: LabelView())
关于swift - 如何在 Swift 中将泛型类型约束为另一个泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33983588/