Construction process and stage construction of the destructor process
Swift's construction process is divided into two stages:
- In the first stage, each stored-type property sets the initial value by introducing its own constructor.
- The second stage is to further customize the storage-type properties before new instances are ready for use.
Security checks
During the construction process, Swift carries out four security checks.
Security 1
Specifies that the constructor must ensure that all properties introduced by its class must be initialized before the other construction tasks can be proxied up to the constructor in the parent class.
For example, the following code is wrong:
classFood {varNameStringInit (Name:String) {self.name = name}}classRecipeingredient:food {varQuantity:int Init (name:String, Quantity:int) {super.init (name:name)//error!self.quantity = Quantity}}
Security 2
Specifies that the constructor must first call the parent class constructor on the proxy, and then set the new value for the inherited property. If this is not done, the new value given by the specified constructor is overwritten by the constructor in the parent class.
For example, the following code is wrong:
classFood {varNameStringInit (Name:String) {self.name = name}}classRecipeingredient:food {override init (name:String) {Self.name ="Why" //error!Super.init (Name:name)}}
Security 3
The convenience constructor must first invoke the other constructors in the same class, and then assign a new value to any property. If this is not done, the new value given by the convenience constructor will be overwritten by the other specified constructors in the same class.
For example, the following code is wrong:
classFood {varNameStringInit (Name:String) {self.name = name}}classRecipeingredient:food {varQuantity:int Init (name:String, quantity:int) {self.quantity = Quantity Super.init (name:name)} Override convenience init (name:String) {quantity =2 //error!Self.init (name:name, Quantity:1) }}
Security 4
The constructor cannot call any instance method, cannot read the value of any instance property, or reference the value of self until the first stage of construction is complete.
For example, the following code is wrong:
classFood {varNameStringInit (Name:String) {self.name = name}}classRecipeingredient:food {varQuantity:int Init (name:String, quantity:int) {self.quantity = Quantity println (self.name)//error!Super.init (Name:name)} Override convenience init (name:String) {Self.init (name:name, Quantity:1) }}
The process of destruction
There can be at most one destructor per class. Destructors do not have any parameters, and no parentheses:
Deinit { //Perform the destruction process }
Subclasses inherit the parent class's anti-initialization function, releasing the subclass and releasing the parent class first.
Recently the company project is a little busy, first so much.
References
- Initialization
- Deinitialization
[SWIFT]DAY11: Construction process and destruction process