Synthesized memberwise initializers for base classes?

(Bruno Rocha) #1

I've been spoiled by the generated memberwise initializer for structs.

struct Foo {
    let bar: Int

let foo = Foo(bar: 1)

It's a nice little touch that reduces boilerplate and speeds development, and it always bugs me that we don't have that for base classes besides the regular MyClass() init when every property already has a default value.

Was there a compiler reason for that to never be implemented? I've found SE-0018 which mentions the compiler's missing features for synthesized inits, but I couldn't determine if there was a deeper reason for their absence or if they were simply not developed.

(Suyash Srijan) #2

I pitched it here: Synthesized initialiser for classes, just like structs

Would be really nice if we had synthesised inits for classes as well!

(Happy Human Pointer) #3

If you have a class

class Foo { 
  let bar: Int 
  required init(bar: Bar) { = bar }
class Baz: Foo {
  let qux: Qux
  override required init(bar: Bar) {
    self.qux = .zero
    super.init(bar: bar)

let type: Foo.Type = Baz.self
type.init(bar: Bar())

How would the compiler know which init to use when it is synthesized?

(Suyash Srijan) #4

The code you've provided is incorrect (calling init on a metatype means you need a required init) - do you have a different example that describes the potential problem?

(Adrian Zubarev) #5

That is a bug in current Swift that isn't diagnosed, but it's fixed in Swift 5.

(Alejandro Alonso) #6

Here are some tweets describing potential issues.

(Matthew Johnson) #7

I was the author of SE-0018. As you can tell by the number, I wrote it very early in the life of SE - in fact it was the first proposal I worked on. I now consider attempting to include classes a mistake that greatly increased the complexity of the proposal. I still believe we should significantly improve synthesized initializers for structs but wouldn't try to include classes if I worked on it again.

(Bruno Rocha) #8

Thanks for sharing this Alejandro! I assumed that supporting subclasses would be problematic which is why I specifically mentioned base classes in this thread, but seeing these makes me think that perhaps implementing it for a specific subset of classes wouldn't end up being a good decision in the long run.

(Happy Human Pointer) #9

@suyashsrijan Sorry about that, I was just trying to provide a quick example.