swift - 返回 Self 类型的下标和不需要在每个子类中覆盖它的需求

标签 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

最佳答案

最简单的方法是使用协议(protocol)扩展:

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

关于swift - 返回 Self 类型的下标和不需要在每个子类中覆盖它的需求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39768149/

相关文章:

Swift 使用解除警报消息

ios - Swift 2.0 ContactsUI 框架

ios - 在 Swift + Sprite Kit 中更改场景的最简单方法

ios - 创建 switch 语句给我错误

ios 在应用程序中访问负载配置文件

ios - 在 Swift 2 中重新加载数据时,如何防止表格格式发生变化?

Swift 2 错误处理和 while

swift - 无法在 Swift 2.0 中使用类型为 (String, [String]) 的参数列表调用 `join`

javascript - Swift:如何使用 JavascriptCore 调用已加载文件中的函数

ios - UIButton 标签检测点击特定文本