[英]Passing self into initializer as delegate within own initializer
might be a silly question, but I'm trying to understand better why I can't do this.可能是一个愚蠢的问题,但我试图更好地理解为什么我不能这样做。 I recall this working in Swift 5.6.1, but I recently updated to Swift 5.7.2.
我记得这个在 Swift 5.6.1 中工作,但我最近更新到 Swift 5.7.2。
Before asking, I want to note that I did see this question: Swift passing self as argument in class init , but it didn't quite answer my question.在提问之前,我想指出我确实看到了这个问题: Swift passing self as argument in class init ,但它并没有完全回答我的问题。 Or maybe I just want to see if these are the only solutions...
或者也许我只是想看看这些是否是唯一的解决方案......
I have a couple of classes that's something like this.我有几个类是这样的。
class Bar {
weak var delegate: FooDelegate?
init(delegate: FooDelegate) {
self.delegate = delegate
}
}
class Foo: FooDelegate {
var bar: Bar
init() {
self.bar = Bar(delegate: self)
}
}
Before I updated, I don't remember this throwing any errors.在我更新之前,我不记得这会引发任何错误。 Now I'm getting the error
Variable 'self.bar' used before being initialized
.现在我收到错误
Variable 'self.bar' used before being initialized
。
Is there a way to set this up so that I'm passing the delegate correctly?有没有办法设置它以便我正确地传递委托?
Thanks all!谢谢大家!
You can solve this by breaking it up in two steps, create the Bar
object and then set delegate
您可以通过分两步解决这个问题,创建
Bar
object 然后设置delegate
init() {
bar = Bar()
bar.delegate = self
}
Of course this requires a new init
for the Bar
class当然这需要一个新的
init
Bar
class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.