In language Swift, to initialise an instance, one has to fill in all of the fields of that class, and only then call superconstructor:
class Base {
var name: String
init(name: String) {
self.name = name
}
}
class Derived: Base {
var number: Int
init(name: String, number: Int) {
// won't compile if interchange lines
self.number = number
super.init(name)
}
}
For me it seems backwards, because the instance needs self
to be created prior to assigning values to its fields, and that code gives impression as if the chaining happens only after the assignment. Apart from that, superclass has no legal means of reading its subclass' introduced attributes, so safety does not count in this case.
Also, many other languages, like JavaScript, and even Objective C, which is somewhat spiritual ancestor to Swift, require chaining call before accessing self
, not after.
What is the reasoning behind this choice to require the fields to be defined before calling the superconstructor?