【问题标题】:Extension for CollectionType with element of certain type ignores subtypes具有特定类型元素的 CollectionType 扩展忽略子类型
【发布时间】:2015-08-31 14:00:51
【问题描述】:

我正在尝试为包含特定类型 FooType 元素的集合类型创建扩展,这很好用:

extension CollectionType where Generator.Element == FooClass
{
    func doSomething()
}

let collectionType = [FooClass]()
collectionType.doSomething()

我的问题是我还希望这个扩展适用于包含 Foo 类的子类的集合类型:

let collectionType = [FooSubclass]()
collectionType.doSomething()    // Doesn't work

我可能会覆盖“==”运算符并遍历超类链,直到找到匹配项,但不确定这是否是正确的方法。

public func ==(t0: Any.Type?, t1: Any.Type?) -> Bool

我是否在 where 子句中遗漏了可以解决此问题的内容,还是我做错了?

【问题讨论】:

    标签: swift generics swift2 swift-extensions


    【解决方案1】:

    使用: 而不是==。

    试试:

    extension CollectionType where Generator.Element: FooClass {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多