Reputation: 25
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(). Now, A will not implement b() and B will not override a(), but a() will be calling b(). In order to do this, I'm trying to use protocol ADelegate, which is a delegate that contains b(). B inherits A and abide by ADelegate. Hence, B must implement b(). Now, say I create an instance of B, let's call it bb. I call bb.a(), which will be calling 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? I think this can be done in Objective C, but I'm not sure how to do in 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.
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?
Upvotes: 0
Views: 101
Reputation: 57114
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()
Upvotes: 1