Why it is called the Memberwise Initialiser

一世执手 提交于 2019-12-21 20:09:53

问题


Quote from the office Swift Document

All structure have an automatically-generated memberwise initializer, which you can use to initialize the member properties of new structure instances ...

Question 1: What is so special about the default initializer, why can't it be simply called the default initializer? Why adding the "memberwise"? Is it because it lists out all the member properties defined in the Structure. And you also have to follow the order defined inside the Structure when creating an instance.

Question 2 Is there any other special initializers who have their own special name? If so, what they look like.

[Note Part I:] For further discuss with Mr. Vadian

[Note Part II:]


回答1:


Regarding question 1:

There is an irrevocable law in Swift:

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

We are talking about structs:

When creating a struct you can use the default initializer (the pair of parentheses) if all properties have a default value.

If you just declare the properties without a default value, the compiler creates an implicit memberwise initializer – which you have to use – to make sure to assign a default value to each property in a very convenient way




回答2:


This seems primarily opinion based, and not a good fit for SO, but here's my 2 cents:

  1. Default sounds a lot like Designated, which is a completely orthogonal concept.

  2. Not "special", but there are at least 2 different kinds of initializers: designated and convenience.



来源:https://stackoverflow.com/questions/38001021/why-it-is-called-the-memberwise-initialiser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!