本文介绍了在swift中从其基类返回一个子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许超类中的方法返回子类的实例,以便我可以在父级和子级上使用方法链接。

I am trying to allow a method in a super class to return an instance of the subclass so that I can use method chaining with methods across both the parent and the child.

但是,当我尝试链接方法时,我收到错误BaseClass没有名为someOtherChainableMethod的成员。这是我的代码:

However, I am getting the error "BaseClass does not have a member named someOtherChainableMethod" when I attempt to chain the methods. Here is my code:

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

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

let childClass = ChildClass

childClass.someChainableMethod().someOtherChainableMethoid()

问题似乎是父链式方法中的'return self'返回一个类型为的实例 BaseClass 而不是 ChildClass

The issue seems to be that the 'return self' in the parent chain-able method is returning an instance with type BaseClass rather than ChildClass.

我也尝试过这是泛型和失败,这是我尝试的:

I have also tried this with generics and failed, this is what I tried:

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

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

let childClass = ChildClass

childClass.someChainableMethod().someOtherChainableMethoid()

在这种情况下,来自 BaseClass的错误 someChainableMethod 方法,是BaseClass不能转换为T。

In this case the error from the BaseClass someChainableMethod method, is "BaseClass is not convertible to T".

推荐答案

您的代码如果您将方法的返回类型更改为自我

Your code works if you change the return type of the methods to Self:

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

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

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

这篇关于在swift中从其基类返回一个子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:46