Generalized and Specialized init Methods for Classes

A couple of things.

First, in swift the with is implied in the first parameter name, so by convention you don't include as part of your argument name. So use

init(superClassParam: Int) { ... }

instead of

init(withSuperClassParam: Int) { ... }

Second, in your case, you don't need to use self to access your class properties. You'll see that pattern when you've used parameter names that match property names, so the property names are hidden and must be addressed specifically using self. But here, your parameters in init are different than the property names, so you're okay.

As for your question, you have a few options.

You could use default values for the parameters to init to solve your issue and replace all of your init methods with something like this:

init(someParam: Int = 1, superClassParam: Int? = nil) {
    memOne = someParam
    memTwo = 2
    memThree = 3
    memFour = 4
    if let param = superClassParam {
        super.init(superClassParam: param)
    } else {
        super.init()
    }
}

Or, you could just set the default values for your properties instead of setting them in your initializer like this:

class SubClass : SuperClass {

    var memOne = 1
var memTwo = 2
var memThree = 3
var memFour = 4

    // We will have defined an init() in the superclass, so we'll need the override keyword here.
    override init() {
        super.init()
    }

    init(someParam: Int) {
        self.memOne = someParam
        super.init()
    }

    // Renamed the parameter so we don't have to use the override keyword. If you want to keep the argument name as superClassParam, just decorate this initializer with override
    init(superParam: Int) {
        super.init(superClassParam: superParam)
    }
}

and of course, you can combine the two ideas and replace all three of the init methods in that last example with this:

init(someParam: Int = 1, superClassParam: Int? = nil) {
    memOne = someParam
    if let param = superClassParam {
        super.init(superClassParam: param)
    } else {
        super.init()
    }
}

I haven't actually tried that code in a playground, but it should get the point across.

/r/swift Thread