下标返回自我类型和不需要的重写它在每个子类中

时间:2016-09-29 10:44:17

标签: swift swift2

有没有办法从subscript返回当前类型,以避免覆盖每个子类的下标,这就是我正在寻找的。

我们不能使用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

1 个答案:

答案 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
    }
}