Inheritance 在swift中从基类返回子类

Inheritance 在swift中从基类返回子类,inheritance,swift,Inheritance,Swift,我试图允许超类中的方法返回子类的实例,这样我就可以在父类和子类之间使用方法链接 但是,当我尝试链接这些方法时,会出现错误“基类没有名为SomeOtherChaineableMethod的成员”。这是我的密码: class BaseClass { func someChainableMethod() -> BaseClass { return self } } class ChildClass: BaseClass { func someOtherC

我试图允许超类中的方法返回子类的实例,这样我就可以在父类和子类之间使用方法链接

但是,当我尝试链接这些方法时,会出现错误“基类没有名为SomeOtherChaineableMethod的成员”。这是我的密码:

class BaseClass {
    func someChainableMethod() -> BaseClass {
        return self
    }
}

class ChildClass: BaseClass {
    func someOtherChainableMethod() -> ChildClass {
        return self
    }
}

let childClass = ChildClass

childClass.someChainableMethod().someOtherChainableMethoid()
问题似乎是父链可重用方法中的“返回自我”返回类型为
BaseClass
的实例,而不是
ChildClass

我也尝试过使用泛型,但失败了,这就是我尝试的:

class BaseClass<T> {
    func someChainableMethod() -> T {
        return self
    }
}

class ChildClass: BaseClass<ChildClass> {
    func someOtherChainableMethod() -> ChildClass {
        return self
    }
}

let childClass = ChildClass

childClass.someChainableMethod().someOtherChainableMethoid()
类基类{
func somechaineablemethod()->T{
回归自我
}
}
类ChildClass:BaseClass{
func someotherchaineablemethod()->ChildClass{
回归自我
}
}
让childClass=childClass
childClass.SomeChaineableMethod().SomeOtherChaineableMethodOID()

在这种情况下,
BaseClass
somechaineablemethod
方法的错误是“BaseClass不能转换为T”。在基类中添加
someotherchainegablemethod
,并留下一个空的实现。

既然您已经知道childClass是childClass的一个实例,您可以这样做

(childClass.someChainableMethod() as ChildClass).someOtherChainableMethoid()

如果将方法的返回类型更改为
Self
,则代码可以工作:

class BaseClass {
    func someChainableMethod() -> Self {
        return self
    }
}

class ChildClass: BaseClass {
    func someOtherChainableMethod() -> Self {
        return self
    }
}

let childClass = ChildClass()
let foo = childClass.someChainableMethod().someOtherChainableMethod()

只需重写基类SomeChaineTableMethod

class BaseClass {
    func someChainableMethod() -> Self{
        return self
    }
}

class ChildClass: BaseClass {
    override func someChainableMethod() -> Self {
        return self
    }
    func A(){

    }
}

var objChild = ChildClass()
objChild.someChainableMethod()

问题是someOtherChaingableMethod方法实际上是特定于ChildClass的。有多个子类具有特定的方法,我不想用它们污染我的基类。或者你可以将你的链方法提取到一个协议中,让所有类实现该协议并在你的链方法中响应该协议。你不能通过继承来实现这一点,因此基类不知道子类的方法。污染所有的链式方法到你的基类,你也可以有多态性。