Simple syntax for Swift's entry (vi)

Source: Internet
Author: User
Tags closure

KVC Dictionary to model constructors
/// `重写`构造函数////// - parameter dict: 字典////// - returns: Person 对象init(dict: [String: AnyObject]) { setValuesForKeysWithDictionary(dict)}
    • The above code compilation will be an error!
    • Reason:

      • KVC is OC-specific, KVC is essentially in 运行时 , dynamically sending methods to objects setValue:ForKey: , setting values for the properties of the object
      • Therefore, before using the KVC method, you need to make sure that the object is properly实例化
    • Add super.init() also will error

    • Reason:

      • 必选属性Initialization assignment must be done before calling the parent class constructor
    • Modify the required parameter to an optional parameter, and 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) "}        
    • setValuesForKeysWithDictionaryThe 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 constructorsDesignated
    • convenienceThe constructor of the keyword decoration is to facilitate the constructor function
    • Convenience constructors have the following characteristics:
      • Can returnnil
      • Only the convenience constructor can call theself.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 returnnil
    • Convenience constructors cannot be overridden
Lazy Loading

Lazy loading is ubiquitous in IOS development

    • Lazy loading format is as follows:
var person: Person = {    print("懒加载")    return Person()}()
    • Lazy loading is essentially a closed package
    • The above code can be rewritten in the following format
let personFunc = { () -> Person in    print("懒加载") return Person()}lazy var demoPerson: Person = self.personFunc()
    • A simple notation for lazy loading
var demoPerson: Person = Person()



Read-only property getter & Setter
    • getter & setterrarely used in Swift, the following code is for information only
var _name: String?var name: String? {    get { return _name } set { _name = newValue }}
Storage-Type Properties & computed properties
    • Storage-type properties-need to open up space to store data
    • Computed properties-Execution functions return other memory addresses
var title: String {    get {        return "Mr " + (name ?? "") }}
    • A property that implements only getter methods is called a computed property, equivalent to the ReadOnly attribute in OC
    • Computed properties themselves do not occupy memory space
    • You cannot set a value for a computed property
    • Computed properties can use the following code shorthand
var title: String {    return "Mr " + (name ?? "")}
Comparison of computed properties with lazy loading
    • Computed properties
      • Do not allocate independent storage space to save calculation results
      • Executed each time it is called
      • More like a function, but cannot receive parameters, and must have a return value
var title2: String {    return "Mr" + (name ?? "")}
    • Lazy Load Properties
      • When the first call is performed, the closure is executed and the value returned by the space storage closure is allocated
      • Separate storage space is allocated
      • Unlike OC, the Lazy property is not called again even if it is set to nil
var title: String = {    return "Mr " + (self.name ?? "")}()

Simple syntax for Swift's entry (vi)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.