swift - 如何在 Swift 中将泛型类型约束为另一个泛型类型?

标签 swift generics inheritance

我想做这样的事情:

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/

相关文章:

swift - 雪碧包 : Animate node with running atlas and move node

swift - 如何从 Swift 中的可选类型获取解包类型?

c# - 使用通用类型的 EntityFramework 的 CRUD 操作

python - 如何从使用构建器实例化的类继承?

c# - 将填充的 List<BaseClass> 转换为 List<ChildClass>

java - 继承类的 protected 静态成员

ios - 如何覆盖 .swift 中的 oc 类别方法

ios - OneSignal 按推送通知去 View Controller iOS Swift

python - 如何访问 typing.Generic 的类型参数?

java - 如何传递 `Class<T>` 的 `List<MyDevice>` ?