Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

ios - Why doesn't Swift provide classes memberwise initializers?

Why are memberwise initialisers provided for structures only?

Do I need to write the initialisers by myself?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...