Synthesized memberwise initializers for base classes?

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.

1 Like

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

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

If you have a class

class Foo { 
  let bar: Int 
  required init(bar: Bar) { self.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?

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?

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

1 Like

Here are some tweets describing potential issues.

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.

1 Like

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.

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