Import UIKit class Person:nsobject {var name:string? var age:int = 0//1. Overriding the initialization method of the parent class override Init () {//In the constructor, if Super.init () is not explicitly called, the system will automatically call you Super.init () Super.init () print ("-------")}//2. Custom constructor, directly append parameter init (name:string, Age:int {self.name = name Self.age = age}/*//3.1 custom constructor, use dictionary as parameter (first method) init (dict: [Stri Ng:any]) {Let tempName1 = dict["name"]//The tempName1 obtained at this time is any. Any optional type let TempAge1 = dict["age"]//The TempAge1 obtained at this time is any. Any optional type//as? The final type to be turned into is an optional type//as! the final converted type is a deterministic type let tempName2 = tempName1 as? string//The tempName2 obtained at this time is a string. Any type of string name = TempName2//swift is a strongly typed language, only the same type can be assigned a value//the First Age assignment method is unsafe if the dictionary does not have an age parameter that crashes//l ET tempAge2 = TempAge1 as! int//The resulting tempAge2 is an int int type//age = TempAge2//swift is a strongly typed language, only the same type can be assigned a value//Second Age assignment method, such as No age parameter in the dictionary does not cause a crash if Let Tempage = TempAge1 as? int {//convert any optional type to int first. Optional type, then use optional binding to get int value self.age = tempage}}*///3.2 Custom constructor, use dictionary as parameter (second method) init (Dict:[string:any]) {super.init () Setvaluesforkeys (DICT)}//Avoid parameters passed in the dictionary parameter in the class
Override this method if the corresponding property is not defined to cause a crash, overriding Func SetValue (_ Value:any?, Forundefinedkey key:string) {}}
Create Person Object Let P1 = person ()//use a parameter construct to create a person object let P2 = person (name: "Zhengyanfeng", age:18) print (p2.name!,p2.age)
Create an object using a dictionary-based argument construct let P3 = person (dict: ["Name": "Zhengyanfeng", "age": +, "height": 1.88]) print (p3.name!, p3.age)