One of the many useful features of Swift’s struct is that they come with a synthesized memberwise initializer, letting us create new instances of the struct just by specifying its properties. However, Swift’s classes don’t have this feature, which is annoying – but why don’t they have it?
The main reason is that classes have inheritance, which would make memberwise initializers difficult to work with. Think about it: if I built a class that you inherited from, then added some properties to my class later on, your code would break – all those places you relied on my memberwise initializer would suddenly no longer work.
So, Swift has a simple solution: rather than automatically generating a memberwise initializer, authors of classes must write their own initializer by hand. This way, you can add properties as much as you want without affecting the initializer for your class, and affecting others who inherit from your class. And when you do decide to change your initializer, you’re doing yourself, and are therefore fully aware of the implications for any inheriting classes.
SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.
Link copied to your pasteboard.