Swift - 在超类的重写函数中返回子类类型

Chr*_*rys 0 ios swift

我正在尝试快速实现可链接的对象设计。这是我的结构:

class A{
    func get() -> some A{
        return self
    }
}

class B:A{
    func set(){

    }
}
Run Code Online (Sandbox Code Playgroud)

我可以创建一个即使我创建原始类的子类也能工作的方法吗?在我的示例中,如果我调用getB我将获得一个A没有名为set.

let b = B()
b.get().set() // A has no member 'set'
Run Code Online (Sandbox Code Playgroud)

因此,要使其正常工作,我必须手动覆盖 fromA中的每个函数,B这并不是最糟糕的,因为我可以调用 super 但仍然浪费时间和重复代码。

Mar*_*chi 6

如果您真的不需要使用带有some关键字的不透明类型,您可以使用协议和扩展获得您想要的内容:

protocol Chainable { 
    func get() -> Self 
} 
extension Chainable { 
    func get() -> Self { 
        return self 
    } 
} 
class A: Chainable {}
class B: A { 
    func set() { 
        print("ok") 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

现在您可以获得get函数所需的返回类型:

let a = A()
a.get() // Type = A
let b = B()
b.get() // Type = B
b.get().set() // Prints 'ok'
Run Code Online (Sandbox Code Playgroud)

如果您不需要在多个类层次结构中重用它,解决方案可以更简单(感谢@Joakim Danielson 指出这一点):

class A {
    func get() -> Self { 
        return self 
    }
}
class B: A {  
    func set() {  
        print("ok")  
    }  
} 
Run Code Online (Sandbox Code Playgroud)

  • 您也可以不使用协议,并在“A”中使用“get”的默认实现 (3认同)