Swift 中的通用 class 继承

Generic class inheritance in Swift

我有以下 class:

class BaseCache<T: Equatable>: NSObject {

    var allEntities = [T]()

    // MARK: - Append

    func appendEntities(newEntities: [T]) {
        ....
    }
}

现在我想子class它,但我得到烦人的错误,我的类型"does not conform to protocol 'Equatable'":

Swift 中的泛型似乎是真实的 pain-in-the-ass。

您对 TrackingCache 的 class 定义是错误的。它重复通用参数:

class TrackingCache<AftershipTracking>: BaseCache<AftershipTracking> { }

应该省略:

class TrackingCache: BaseCache<AftershipTracking> { }

这会触发潜在的 swift 错误 Classes derived from generic classes must also be generic。您可以通过指定需要成为或继承自 AftershipTracking 的类型参数来解决此问题:

class TrackingCache<T: AftershipTracking>: BaseCache<AftershipTracking> { }

完整示例:

class BaseCache<T: Equatable>: NSObject {
  var items: [T] = []

  func appendItems( items: [T]) {
    self.items += items
    didAppendItems()
  }

  func didAppendItems() {} // for overriding
}

class AftershipTracking: NSObject {
  var identifier: Int
  init( identifier: Int) {
    self.identifier = identifier
    super.init()
  }
}

extension AftershipTracking: Equatable { }

func ==( lhs: AftershipTracking, rhs: AftershipTracking) -> Bool {
  return lhs.identifier == rhs.identifier
}

class TrackingCache<T: AftershipTracking>: BaseCache<AftershipTracking> {
  override func didAppendItems() {
    // do something
  }
}

let a = TrackingCache<AftershipTracking>()
let b = TrackingCache<AftershipTracking>()

a.appendItems( [AftershipTracking( identifier: 1)])
b.appendItems( [AftershipTracking( identifier: 1)])

let result = a.items == b.items // true

这应该有效:< swift 4 >

class TrackingCache<T: AftershipTracking>: BaseCache<T>

另一个例子:

protocol P {

}

class C: P {

}

class CS: C {

}

class L<T:P> {
    let c: T

    init(_ c: T) {
        self.c = c
    }
}

class LS<T:CS>:L<T> {

}

let i = LS(CS())

i.c

c 现在是 CS