Home > Blockchain >  Passing self into initializer as delegate within own initializer
Passing self into initializer as delegate within own initializer

Time:12-29

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.

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. 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.

Is there a way to set this up so that I'm passing the delegate correctly?

Thanks all!

CodePudding user response:

You can solve this by breaking it up in two steps, create the Bar object and then set delegate

init() {
    bar = Bar()
    bar.delegate = self
}

Of course this requires a new init for the Bar class

  • Related