Swift alternative to using instance member as default parameter

Viewed 60

Here is a toy version of my problem:

class MainClass {
    let toPass: ToPassProtocol
    let otherClass: BbbProtocol
    init(
        toPass: ToPassProtocol,
        otherClass: Bbb = Bbb(toPass: toPass)
    ) {
        self.toPass = toPass
        self.otherClass = otherClass
    }
}

class Bbb: BbbProtocol {
    let toPass: ToPassProtocol
    init(toPass: ToPassProtocol) {
        self.toPass = toPass
    }
}

protocol ToPassProtocol {}
class ToPass: ToPassProtocol {}

protocol BbbProtocol {}

Which gives the error Cannot use instance member toPass as a default Parameter

So without using a function to pass ToPassProtocol after initialisation, how can I pass this class as, well, a parameter?

1 Answers

if you already have the toPass being passed, change your init function to use the passed parameter and have the other default to nil:

    init(
        toPass: ToPassProtocol,
        otherClass: Bbb? = nil
    ) {
        if let otherClass = otherClass {
          self.otherClass = otherClass
        } else {
          self.otherClass = Bbb(toPass: toPass)
        }
        self.toPass = toPass
    }
Related