Jonathan Bronson Jonathan Bronson - 3 years ago 225
Swift Question

In Swift 3, is it possible for a subclass to inherit defaults from its superclass?

In Swift 3 is possible to create a subclass that inherits default parameters from its superclass. E.g.,:

class ParentClass {
let red: Double

init(red: Double = 1.0) {
self.red = red
}
}

class ChildClass: ParentClass {
let blue: Double

init(blue: Double = 2.0) {
self.blue = blue
super.init()
}
}


I'd like to be able to create instances of ChildClass such that if I specify the value of red (e.g.,
let foo = ChildClass(red: 10.0)
) then I can set its value but if I don't then it's value will be the default (e.g.,
let bar = ChildClass()
will have
bar.red = 1.0
).

Is this possible? The above doesn't work, but it's conceptually what I'd like. Additionally, I do not want to set the default value of red again in ChildClass (that defeats half the value of the superclass).

If something similar is better accomplished with structures or protocols that would work as well.

Thanks!

Answer Source

If I understood correctly, this works:

class ParentClass {
    let red: Double

    init(red: Double = 1.0) {
        self.red = red
    }
}

class ChildClass: ParentClass {
    let blue: Double

    init(blue: Double = 2.0, red: Double? = nil) {
        self.blue = blue

        if let red = red {
            super.init(red: red)
        } else {
            super.init()
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download