简体   繁体   English

快速地,超类的函数如何通过协议/委托使用子类的函数?

[英]In swift, how can a superclass's function uses subclass's function through protocol/delegate?

So I'm writing an iOS app with Swift, and I encounter the following problem: I have two class A and B, while B is the subclass of A. Let A has a function a(), and B has a function b(). 所以我用Swift编写了一个iOS应用,遇到了以下问题:我有两个类A和B,而B是A的子类。让A有一个函数a(),而B有一个函数b( )。 Now, A will not implement b() and B will not override a(), but a() will be calling b(). 现在,A将不会实现b(),B将不会重写a(),但是a()将调用b()。 In order to do this, I'm trying to use protocol ADelegate, which is a delegate that contains b(). 为此,我尝试使用协议ADelegate,它是一个包含b()的委托。 B inherits A and abide by ADelegate. B继承A并遵守ADelegate。 Hence, B must implement b(). 因此,B必须实现b()。 Now, say I create an instance of B, let's call it bb. 现在,假设我创建了一个B的实例,我们称之为bb。 I call bb.a(), which will be calling b(). 我叫bb.a(),它将叫b()。 A's a() is called since a() is only implemented in superclass A. Because of this use case, in my implementation of class A, I must call b() (I think there's no way around according to my use case), while b() is only implemented by A's subclass B. My question is, how can I call b() correctly in A? 之所以调用A的a()是因为仅在超类A中实现了a()。由于这种用例,在我的类A的实现中,我必须调用b()(我认为根据我的用例无法解决),而b()仅由A的子类B实现。我的问题是,如何在A中正确调用b()? I think this can be done in Objective C, but I'm not sure how to do in Swift. 我认为这可以在Objective C中完成,但是我不确定如何在Swift中完成。 What I'm doing now is something like this: 我现在正在做的事情是这样的:

var delegate: ADelegate?  // this code is in A
...
self.delegate?.b()

However, I don't know how to assign value to delegate. 但是,我不知道如何为代理分配值。 Note that the only instance created is bb() which is an instance of B. 请注意,创建的唯一实例是bb(),它是B的实例。

protocol ADelegate {
    func b()
}

class A: NSObject {
    var delegate: ADelegate?

    func a() {
        self.delegate?.b()
    }
}

class B: A, ADelegate {

    func b() {

    }
}

use case: 用例:

x = B()
x.a()

This is what I have right now, I just want to know how should I assign to self.delegate in A? 这就是我现在所拥有的,我只想知道如何分配给A中的self.delegate?

The following works - not making much sense to be itself delegate but okay, it works: 以下工作-本身没有太大意义,但是可以,它可以工作:

let x = B()
x.delegate = x
x.a()

Or a little bit more separated: 或更分开一些:

let x = B()
let a : A = x
a.delegate = x
a.a()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM