【发布时间】:2015-11-29 13:55:36
【问题描述】:
我想做这样的事情:
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)
或扩展 Config 类:
class RedLabelConfig<T:UILabel> : RedViewConfig<T> {
func configure(x:T) {
super.configure(x)
x.textColor = .redColor();
}
}
Config.apply(RedLabelConfig(), to:label)
我尝试这样做,但我无法约束类。所以我尝试使用协议和关联类型,但是在子类化时,我发现覆盖关联类型时出现问题 (like this)。
【问题讨论】:
标签: swift generics inheritance