有没有办法从subscript
返回当前类型,以避免覆盖每个子类的下标,这就是我正在寻找的。 p>
我们不能使用Self
作为下标的返回类型,因为它不被允许但是可能有一些解决方案?
示例:
class A {
var array = [Int]()
init(array: [Int]) {
self.array = array
}
subscript(condition: (Int) -> Bool) -> A {
get {
return A(array: array.filter(condition))
}
}
}
class B: A {
func aImB() -> Bool {
return true
}
}
let array = [1, 2, 3, 4, 5]
let objB_1 = B(array: array)
let objB_2 = objB_1[{ $0 > 3}]
print(objB_2.dynamicType) // -> will print "A" but I would like to see "B"
objB_2.aImB() // can't be called because objB_2 is of the type A
答案 0 :(得分:1)
最简单的方法是使用协议扩展:
protocol MyProtocol {
var array:[Int] {get set}
init(array: [Int])
}
extension MyProtocol {
subscript(condition: (Int) -> Bool) -> Self {
get {
return Self(array: array.filter(condition))
}
}
}
class A:MyProtocol {
var array = [Int]()
required init(array: [Int]) {
self.array = array
}
}
class B: A {
func aImB() -> Bool {
return true
}
}