As per title.
Because of the required init(a:), I can't initialize 'b', unless I resort to overloading as above.
Question (1):
Is there a better way of approaching this? It seems a little off looking at self.b=0 has to be included there.
class BaseClass {
var a: Int
required init(a: Int) {
self.a = a
}
}
class SubClass: BaseClass {
var b: Int
init(b: Int, a: Int){
self.b = b
super.init(a: a)
}
required init(a: Int) {
self.b = 0 // have to put something here, otherwise complain
super.init(a: a)
}
}
Then, calling, e.g.:
let mySubClass = SubClass(b:2, a:3) //works by calling init(b:a:)
note: another workaround is resorting to fatal error in required init as such (but again, it kinda doesn't look right):
required init(a: Int) {
// fatal error()
}
Additionally, this brings me to the next question, regarding the example below.
Question (2):
With the presence of a protocol, for example:
protocol RandomProtocol {
init(randomProp: Int)
}
Calling e.g.:
let mySubClassWithProtocol = SubClassWithProtocol(c: 1, a: 2, b: 3) //works ok
Is there a better way of implementing this? again, like above, it seems a little convoluted and counter-intuitive
SubClassWithProtocol below needs to implement required init from RandomProtocol and SubClass:
class SubClassWithProtocol: SubClass, RandomProtocol {
var c: Int
init(c: Int, a: Int, b: Int, randomProp: Int) {
self.c = c
super.init(b: b, a: a)
}
required init(a: Int) {
self.c = 0
super.init(a: a)
}
required init(randomProp: Int) {
//need to call self.c and super.init, otherwise complain
self.c = 0
super.init(b: 0, a: 0)
}
note:
Just starting out with Swift here. Trying to figure out my way around. I understand the questions above probably are more academic than practical. But thanks for any help.