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:
- It will reduce boilerplate in some scenarios as you won't have to manually write those initialisers.
- 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:
- ios - Why doesn't Swift provide classes memberwise initializers? - Stack Overflow
- ios - How to automatically create an initializer for a Swift class? - Stack Overflow
- 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?