swift - 具有特定类型元素的 CollectionType 扩展会忽略子类型

标签 swift generics swift2 swift-extensions

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

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

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

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

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

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

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

我的 where 子句中是否遗漏了一些可以解决此问题的内容,或者我这样做完全错误吗?

最佳答案

使用:而不是==

尝试:

extension CollectionType where Generator.Element: FooClass {

关于swift - 具有特定类型元素的 CollectionType 扩展会忽略子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32313103/

相关文章:

swift - 使用 UIButton Swift 2 更改另一个类中变量的值

ios - 为什么我们不遵循使用 xib 创建 customTableViewCell 的相同过程,就像使用 xib 创建 customView 一样?

swift - __lldb_expr_640.MyClassName 错误?

ios - 拆分 UICollectionView & UICollectionViewDataSource 显示黑屏

Java Generics E extends Comparable<E> 留下警告

swift - 如何重写 Swift++ 运算符? : ternary operator

google-places-api - 无法使用 Xcode 7/iOS9 使用 Google Maps API 在路径错误时加载优化模型

Swift 的内存管理

Java泛型接口(interface)实现不能省略类型参数?

ios - 如何在 Swift 函数中返回泛型参数的默认值?