Swift subplot init has to set all properties before calling super, but the property requires super init to do first
I am trying to write two Swift classes, one of which is a subclass of the other and must take one of the properties of the superclass and use that to customize my self.
class BaseClass {
let someValue: Double
let size: CGSize
init (size: CGSize) {
self.size = size
self.someValue = size.width / 2.0 //Doesn't really matter how this is calculated
}
}
class Subclass: BaseClass {
let someNewValue: Double
override init(size: CGSize) {
super.init(size: size)
self.someNewValue = self.someValue * 2
}
}
The problem is that the subclass requires that it be called super.init
after it has initialized all of its properties. However, the call self.someNewValue = self.someValue * 2
that does this relies on the super init that was called first to install self.someValue
. I guess I could work around this by turning let someValue: Double
in var someValue: Double
in BaseClass and then setting its value in the init subclass as well as the init base class, but that just seems bad.
source to share
I see two solutions here:
Make someNewValue
implicitly expanded optional
class Subclass: BaseClass {
let someNewValue: Double!
override init(size: CGSize) {
super.init(size: size)
self.someNewValue = self.someValue * 2
}
}
or give someNewValue
some default value before calculating its final value
class Subclass: BaseClass {
let someNewValue: Double = 0.0
override init(size: CGSize) {
super.init(size: size)
self.someNewValue = self.someValue * 2
}
}
Both matches shouldn't cause any problems.
source to share