sliwinski.lukas sliwinski.lukas - 2 months ago 8
Swift Question

Subscript returning Self type and unwanted need of overriding it in each subclass

Is there a way to return current type from the

subscript
that would avoid overriding subscript for each subclass and this is what I'm looking for.

We can't use
Self
as the return type of the subscript because it is not allowed but maybe there is some solution?

Example:

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

Answer

The easiest way would be to use a protocol extension:

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
    }
}
Comments