Synthesized initialiser for classes, just like structs

At the moment, when you create a struct, the compiler provides you with a synthesized initialiser:

struct Foo {
  let baz: String
}

// No need for init(...)

but if you do the same with a class:

class Foo {
  let baz: String
}

The compiler will complain: Class Foo has no initialisers and Stored property 'baz' without initial value prevents synthesized initializers, along with a fix-it to assign an empty string to it.

I think it would be helpful if we had a synthesized initialiser for classes as well as:

  1. It will reduce boilerplate in some scenarios as you won't have to manually write those initialisers.
  2. It will also allow you to freely switch between classes and structs by simply changing the type (struct <-> class). This will only apply if you have a simple class or struct and/or you're not doing something custom or complex.

There has been some discussion about it:

  1. ios - Why doesn't Swift provide classes memberwise initializers? - Stack Overflow
  2. ios - How to automatically create an initializer for a Swift class? - Stack Overflow
  3. https://stackoverflow.com/questions/53252865/swift-automatic-synthesized-initializer-for-class-as-for-structs

There was a proposal for it as well (synthesized initialiser for classes was just a part of it), but it was deferred: swift-evolution/0018-flexible-memberwise-initialization.md at master · apple/swift-evolution · GitHub

What does everyone think?

1 Like

I think there’s a recent thread on this very topic:

If we have some new stuff to add, perhaps it would be best to continue there?

1 Like

Oh, somehow I missed this. Thanks!

1 Like