In Swift, both struct and class are used to define custom types, but they have some key differences in behavior. One of these differences is that structs in Swift automatically receive a memberwise initializer by default, whereas classes do not.
The reason behind this design choice is rooted in the fundamental differences between structs and classes. Structs in Swift are value types, which means that when you create an instance of a struct and assign it to a variable or pass it as a function argument, a copy of the entire value is made. On the other hand, classes are reference types, and when you work with them, you are actually dealing with references to the underlying instance.
Given this distinction, the memberwise initializer for structs allows you to easily initialize all the properties of a struct using a single initializer. Since structs are copied when assigned or passed around, having a memberwise initializer simplifies the process of creating new instances.
Classes, being reference types, are often used for more complex scenarios and can have inheritance, deinitializers, and other features that require more explicit initialization logic. Providing a default constructor for classes would require additional considerations and would not be as straightforward as it is for structs.
That said, in Swift, you can still define custom initializers for both structs and classes. If you want a class to have a default constructor, you can define one yourself by providing a parameterless initializer. However, unlike structs, classes do not automatically receive a memberwise initializer.