Construction, destruction, inheritance
constructor Function
When you create an instance of a type, the arguments in the constructor need to write the full parameter name:
struct Color {Let Red= 0.0,Green= 0.0,Blue= 0.0Init(Red: Double,Green: Double,Blue: Double) { Self.Red=RedSelf.Green=GreenSelf.Blue=Blue}}Let Magenta= Color(Red: 1.0, Green: 0.0, blue: 1.0) letverygreen = Color(0.0, 1.0, 0.0)//This reports a compile-time error-external names is RequiRed
In constructors, you can also use closures to initialize properties:
struct Checkerboard {Let Boardcolors: Bool[] = { VarTemporaryboard= Bool[]() VarIsblack= False ForIInch 1...10 { ForJInch 1...10 {Temporaryboard.Append(Isblack)Isblack= !Isblack}Isblack= !Isblack} ReturnTemporaryboard}() func squareisblackatrow (row int, Column: int) -> bool { Boardcolors[(row * 10) +] }}
The boardcolors in the example above is initialized with a closure, and the checkerboard is filled at intervals.
Destructors
Swift handles memory management of instances by automatic reference counting ARC
, freeing instances that are no longer needed to free resources. You can customize the destructor when the code requires additional action. It is important to note that each class can have at most one destructor, with no arguments and parentheses for the destructor:
deinit {// 执行析构过程}
Inheritance
Any class that does not inherit from another class is called a base class. Swift's class is not inherited from a global base class, and all classes that do not inherit other parent classes in the definition of the class are base classes:
Class Vehicle { VarNumberofwheels: Int VarMaxpassengers: int func description ( ) -> string { return "\ (numberofwheels) Wheels Up to \ (maxpassengers) passengers " } Init () { Numberofwheels = Span class= "lit" >0 maxpassengers = 1 }}
inheriting a subclass of a parent class when overriding a function, you must add a override
keyword to indicate that the method is an overriding method, and the benefit is that you can check for a corresponding method in the parent class and not cause some unpredictable errors due to name errors.
Class Car: Vehicle { VarSpeed: Double = 0.0Init() { Super.Init()Maxpassengers= 5Numberofwheels= 4 }override func description () -> string { return super. () + ";" + "Traveling at \ (speed) mph" }} /span>
In addition to overloading functions, the properties of a class can be overloaded in subclasses, such as the getter
and setter
methods:
Class Speedlimitedcar: Car { Override VarSpeed: double { get { return . Speed } set { super.= Min (newvalue,< Span class= "PLN" > 40.0) } }} /span>
Using a @final
tag class, you can prohibit overriding a class, or a method of a class, such as:@final class
Issues to be aware of in the constructor of a subclass:
1、自定义构造函数要先调用自己类默认构造函数,自己重写默认构造函数要先调用父类默认构造函数2、应该要先调用父类的构造函数或者自身的默认构造函数,以防止先给属性赋值了然后才调用父类或者自身的默认构造函数而把之前的赋值覆盖了
iOS Development--swift Chapter &swift new Features (iv) Construction, destruction, inheritance