son‘ has no initializers
-‘Person‘ 类没有实例化器s
Cause: If a required attribute is defined in a class, you must allocate space for these required properties through the constructor and set the initial value
重写
The constructor of the parent class
/// `重写`父类的构造函数override init() {}
Prompt Error- Property ‘self.name‘ not initialized at implicitly generated super.init call
属性 ‘self.name‘ 没有在隐式生成的 super.init 调用前被初始化
- Adding
super.init()
calls Manually
/// `重写`父类的构造函数override init() { super.init()}
Prompt Error- Property ‘self.name‘ not initialized at super.init call
属性 ‘self.name‘ 没有在 super.init 调用前被初始化
- Set the initial value for the required property
/// `重写`父类的构造函数override init() { name = "张三" age = 18 super.init()}
Summary
- Non-Optional property, you must set the initial value in the constructor to ensure that the property is correctly initialized when the object is instantiated.
- Before calling the parent class constructor, you must ensure that the properties of this class have been initialized
- The constructor in Swift does not have to be written
func
Constructors for subclasses
- When customizing a subclass, you need to set the initial values for the properties defined in this class first in the constructor
- Then call the parent class's constructor to initialize the properties defined in the parent class.
/// 学生类class Student: Person { /// 学号 var no: String override init() { no = "001" super.init() }}
Summary
- The constructors of this class are called first to initialize the properties of this class
- Then call the parent class's constructor to initialize the properties of the parent class
- After Xcode 7 Beta 5, the constructor of the parent class is automatically called, strongly recommended
super.init()
, and the readability of the code execution thread is maintained
super.init()
Must be placed after the initialization of this class of properties to ensure all initialization of this class of properties is complete
Optional
Property
- Set the object property type to
Optional
class Person: NSObject { /// 姓名 var name: String? /// 年龄 var age: Int?}
可选属性
Does not need to set the initial value, the default initial value is nil
可选属性
Allocates space when setting values, is deferred allocation space, more in line with the principle of delayed creation in mobile development
Overloaded constructors
- Support for function overloading in Swift, same function name, different parameter types
/// `重载`构造函数////// - parameter name: 姓名/// - parameter age: 年龄////// - returns: Person 对象init(name: String, age: Int) { self.name = name self.age = age super.init()}
Precautions
- If the constructor is overloaded, but the default constructor is not implemented
init()
, the system no longer provides a default constructor
- Cause, when instantiating an object, you must allocate space and set an initial value through the constructor for the object property, and for the class that has the required parameters, the default
init()
cannot complete the allocation space and set the initial value of the work
To adjust the constructor of a subclass
重写
The constructor of the parent class
/// `重写`父类构造函数////// - parameter name: 姓名/// - parameter age: 年龄////// - returns: Student 对象override init(name: String, age: Int) { no = "002" super.init(name: name, age: age)}
/// `重载`构造函数////// - parameter name: 姓名/// - parameter age: 年龄/// - parameter no: 学号////// - returns: Student 对象init(name: String, age: Int, no: String) { self.no = no super.init(name: name, age: age)}
Note: If you are overloading a constructor, you must super
work with the initialization of the parent class property to complete
重载
And
重写
重载
, function name is the same, parameter name/parameter number is different
- Overloaded functions are not just limited to
构造函数
- Function overloading is an important symbol of face object programming language
- Function overloading simplifies programmer's memory
- OC does not support function overloading, which is an alternative to OC
withXXX...
重写
, subclasses need to be extended on the basis of the parent class's own methods, requiring the override
keyword
KVC Dictionary to model constructors
/// `重写`构造函数////// - parameter dict: 字典////// - returns: Person 对象init(dict: [String: AnyObject]) { setValuesForKeysWithDictionary(dict)}
- The code above will be error-compiled!
-
Reason:
- KVC is specific to OC, KVC is essentially a
runtime
that dynamically sends to an object; Setvalue:forkey:
; method to set the value of the object's properties
- Therefore, before using the KVC method, you need to ensure that the object has been properly
instantiated
-
Add super.init ()
also error
-
Cause:
-
Required Properties
must complete initialization assignment before calling the parent class constructor
-
To modify the required parameters to optional parameters, the adjusted code is as follows:
///personal model Class person: nsobject {///name var Name: string? ///ages var Age: int? ///' override ' constructor //////-parameter dict: Dictionary //////-Returns:person object init (dict: [ Span class= "Hljs-type" >string: anyobject]) {super.init () setvaluesforkeyswithdictionary (Dict)}}
Run the test and still get an error
Error message: this class is not key value coding-compliant for the key age.
这个类的键值 age 与 键值编码不兼容
- Reason:
- In Swift, if the property is optional, no space is allocated for the property at initialization time
- The basic data type in OC is
可选
the concept of saving a value that does not exist
- WORKAROUND: Set the initial value for the base data type
- The modified code is as follows:
/// 姓名var name: String?/// 年龄var age: Int = 0/// `重写`构造函数////// - parameter dict: 字典////// - returns: Person 对象init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict)}
Tip: When defining a class, you must set the initial value for the basic data Type property, otherwise you will not be able to set the value correctly using KVC
KVC function Call Order
Init (dict: [String:Anyobject]) {Super.Init () setvaluesforkeyswithdictionary (Dict)}override func setvalue (Value:anyobject, Forkey key:string) {print (" key \ (Key) \ ( Value) super.setvalue (value, Forkey:key)}//' NSObject ' By default, when a key value is found that is not defined, a ' nsundefinedkeyexception ' exception is thrown override func setvalue (Value:anyobject?, Forundefinedkey key:string) {print ( "UndefinedKey \ (key) \ (Value) "}
setValuesForKeysWithDictionary
The function is called in the dictionary by key
repeating the setValue:forKey
- If the function is not implemented
forUndefinedKey
, the program crashes directly
- NSObject default throws an exception when a key value is found that is not defined
NSUndefinedKeyException
- If implemented
forUndefinedKey
, it is guaranteed setValuesForKeysWithDictionary
to continue traversing the subsequentkey
- If the parent class
forUndefinedKey
is implemented, the subclass can no longer implement this function
KVC functions for subclasses
/// 学生类class Student: Person { /// 学号 var no: String?}
- If the parent class has implemented related methods in the parent class, no more related methods are implemented in the subclass
Convenience convenient constructor function
- By default, all constructor methods are specified constructors
Designated
convenience
The constructor of the keyword decoration is to facilitate the constructor function
- Convenience constructors have the following characteristics:
- Can return
nil
- Only the convenience constructor can call the
self.init()
- The convenience constructor cannot be
重写
orsuper
/// `便利构造函数`////// - parameter name: 姓名/// - parameter age: 年龄////// - returns: Person 对象,如果年龄过小或者过大,返回 nilconvenience init?(name: String, age: Int) { if age < 20 || age > 100 { return nil } self.init(dict: ["name": name, "age": age])}
Note: In Xcode, self.init
No smart hints are entered
/// 学生类class Student: Person { /// 学号 var no: String? convenience init?(name: String, age: Int, no: String) { self.init(name: name, age: age) self.no = no }}
Convenient constructor Application scenarios
- Determines whether an object is created based on a given parameter, rather than having to instantiate an object as specified by the constructor
- In practical development, the constructors of existing classes can be extended to simplify the creation of objects with convenient constructors
Summary of constructor functions
- Specifies that the constructor must call the specified constructor of its immediate parent class (unless there is no parent class)
- Convenience constructors must call other
指定构造函数
or used methods defined in the same class self.
父类的便利构造函数
- The convenience constructor can return
nil
- Convenience constructors cannot be overridden
About constructors in Swift