Hi all,
As reported in issue #69965, Swift currently has a hole in it's checking to ensure that a class has initializers. If one writes the following:
class MySuperclass {
required init() { }
init(boop: Bool) {}
}
class MySubclass: MySuperclass {
var hi: String
}
the Swift compiler will reject it with:
error: class 'MySubclass' has no initializers
However, if you put MySuperclass
into one module and MySubclass
into a different module, like this:
// module A
open class MySuperclass {
required public init() { }
internal init(boop: Bool) {}
}
// module B
import A
class MySubclass: MySuperclass {
var hi: String
}
there is no error at all---meaning that one can end up creating MySubclass
instances via the required MySuperclass.init()
initializer without having initialized hi
.
There are three points at which we could have rejected the code:
MySubclass
lacks therequired init()
, which we must diagnoseMySubclass
has no initializers whatsoever, which we could diagnose to be consistentMySuperclass
is markedopen
but cannot be subclassed outside of the module due to the internal designated initializerinit(boop:)
, so we could reject theopen
.
(1) is clearly a bug fix---we have a rule for required initializers, and we are not enforcing it consistently.
(2) is likely a bug fix---there's nothing in the language model that makes this rule less reasonable across modules. As far as I can tell, the carve-out that suppressed the diagnostic was introduced for Objective-C interoperability, because an Objective-C designated initializer might not be importable into Swift, and that Swift classes accidentally got through. We'd likely have to leave the hole in place for classes defined in Objective-C.
(3) is adding a new restriction to open
, so it doesn't feel like a bug fix. However, it does move the error to the point where the mistake was initially made---an open
class that can't be subclassed is almost certainly a mistake. I can't think of any reason why we wouldn't want to reject it.
Thoughts on whether we should introduce the restriction on open
described by (3)?
Doug