9

Why are memberwise initialisers provided for structures only?

Do I need to write the initialisers by myself?

3
  • 4
    This is NOT an opinion-based question. The creators of Swift have decided not to provide such initializers for a reason. There is probably a crucial difference between classes and structs that makes it impossible to provide a memberwise initializers for the classes, and a good answer would reveal that difference. Commented Mar 16, 2016 at 13:47
  • 1
    I doubt that you will get a better answer other than "Chris Lattner didn't like it". Maybe that was his way of promoting structures (value type) over class (reference type). Commented Mar 16, 2016 at 13:48
  • 1
    @EricD. I don't agree. "Can" is not same question as "Why" Commented Mar 16, 2016 at 14:45

1 Answer 1

14

Do I need to write the initialisers by myself?

Yes.

A proposal to extend memberwise initializers to classes and make them more flexible has been discussed exhaustively on the Swift Evolution mailing list in Dec 2015/Jan 2016.

Eventually, the proposal has been rejected for various reasons, with the possibility of revisiting the topic later (after Swift 3 is released).

In the rejection, Chris Lattner noted at least one reason why memberwise initialization was offered specifically for structs: because it makes it possible to write pure "bags of properties", such as Vec4 or CGRect, with minimal overhead:

2) Memberwise init sugar strongly benefits “POD” types and other “bags of property” types (e.g. “Vec4"), and many of the C struct types that Cocoa has (CGRect etc). In these cases, clients often want to initialize all of the fields explicitly and a memberwise init proposal eliminates this boilerplate. This case is what our existing feature attempts to service.

Most classes are probably more complex, and you would want more control over the memberwise initializer, which would have made the feature much more complex, too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.