Swift Fundamentals 4

Source: Internet
Author: User

13. Constructors for classes 1. Introduction to Constructors
    • The constructor is similar to the initialization method in OC: Init method
    • When a class is created by default, a constructor is inevitably called
    • Even if you do not write any constructors, the compiler provides a default constructor.
    • If it is inherited from NSObject, you can override the constructor of the parent class
2. Basic use of constructors 2.1 Basic use of constructors
    • The properties of the class must have a value
    • If the value is not initialized at the time of definition, you can assign a value in the constructor
class person:nsobject var name:stringvar age:int // overridden the construction method of the NSObject (parent class) Override      "0}}//Create a Person object = person ()

2.2 Assigning values to attributes when initializing
    • Many times, when we create an object, we assign a value to the property
    • Constructors can be customized
    • Note: If you customize the constructor, the Init () method is overwritten. That is, there is no default constructor
class person:nsobject var name:stringvar age:int // Custom Constructors Override the Init () function  == Age }}//  Create a Person object  "Ryan"  )

2.3 Dictionary to model (incoming dictionary when initialized)
    • When you actually create an object, it's more about turning the dictionary into a model
    • Attention:

      • Go to the dictionary to take out the nsobject, any type.
      • Can be converted to the desired type by as!, and then assigned (cannot be directly assigned)
classperson:nsobject var name:stringvar age:int//Custom Constructors Override the Init () functionInit (dict:String:NSObject) name= Dict"name"  as!Stringage= Dict" Age"  as!Int}}//Create a Person objectLet dict="name":"Ryan"," Age": -Let p= Person (dict:dict)

2.4 Dictionary to model (using KVC conversion)
    • It is more convenient to use KVC dictionary to turn model
    • Attention:

      • KVC does not guarantee that all properties will be assigned a value
      • Therefore, the property needs to have a default value

        • Base data type default value is set to 0
        • An object or struct type is defined as an optional type (the optional type is nil before it is assigned)
classPerson:nsobject//the type of struct or class, which must be an optional type. Because there is no guarantee that the value will be assignedvar name:string?//The base data type cannot be an optional type, otherwise KVC cannot be convertedvar age:int=0//Custom Constructors Override the Init () functionInit (dict:String:NSObject)//object must be initialized firstSuper.init ()//calling the object's KVC method dictionary to modelsetvaluesforkeyswithdictionary (Dict)}}//Create a Person objectLet dict="name":"Ryan"," Age": -Let p= Person (dict:dict)

14. Closures 1. Introduction of closures
    • Closures are very similar to block in OC

      • Block in OC is an anonymous function
      • Closures in Swift are a special function
      • Block and closures are often used for callbacks
2. Use of closures Review of usage of 2.1 block
    • Classes that define network requests
@interfacehttptool:nsobject-(void) Loadrequest: (void(^) ()) Callbackblock; @end@implementationhttptool-(void) Loadrequest: (void(^) ()) Callbackblock {Dispatch_async (Dispatch_get_global_queue (0,0), ^{NSLog (@"Load Network data:%@", [Nsthread CurrentThread]);d Ispatch_async (Dispatch_get_main_queue (),^{callbackblock ();  }); });}@end

    • Make network requests, request to data and use block for callback
-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *)event        {[ Self.httptool loadrequest:^{NSLog (@ " main thread, callback data.%@", [nsthread  CurrentThread]); }];}

    • Block notation Summary:
block notation:    type:    return value (the name of the block) (parameter of block) value:^(parameter list) {  //  execute code };

2.2 Using closures instead of block
    • Classes that define network requests
class Httptool:nsobject {func loadrequest (callBack: ()) {Dispatch_async (Dispatch_get_global_queue (  00  in print (" load Data " in    callBack ()}) }}}

    • Make network requests, request to data, use closures for callbacks

Override event: Uievent? {        //  network request in                 print (" back to main thread ")  , Nsthread.currentthread ());}        )     }

2.3Closure of the summary of the wording: 2.3.1 Closure of the wording:
Type: (parameter list)--(return value) Tip: Beginner definition closure Type, direct write (), in//  execute code }  

shorthand for 2.3.2 closures
    • If the closure has no parameters, no return value. Contents before and in can be omitted

httptool.loadrequest ({        print (" back to main thread ", Nsthread.currentthread () );     })        

    • Trailing closure notation:

      • If the closure is the last parameter of the function, the closure can be written back
      • If the function has only one parameter and the parameter is a closure, then () can not write
httptool.loadrequest () {       print (" back to main thread ", Nsthread.currentthread ());        }         // This is the recommended formulation in development         httptool.loadrequest {       print (" back to main thread ", Nsthread.currentthread ());        }

2.3.3 circular references for closures
    • If the closure is strongly referenced in the Httptool, a circular reference is formed
class httptool:nsobject {//  define attribute to strongly reference the incoming closure var callBack: (())? func loadrequest (callBack: ()) {Dispatch_async (dispatch_get_global_queue (00 In   print (" load Data "in = CallBack}}

    • Ways to resolve circular references in Swift

// weak var weakself = self;         // [Weak self] ()-         in // [unowned Self] ()-        in inch           = Uicolor.redcolor () print ("Back to Main thread",           Nsthread.currentthread ());        }

15 Lazy Loading 1. Introduction to Lazy Loading
    • Lazy loading is also the way of Swift

      • (Apple's design idea: that all objects are actually loaded into memory when they are used)
    • Unlike OC, Swift has a special keyword to implement lazy loading
    • The Lazy keyword can be used to define an attribute lazy loading
2. Use of lazy loading
    • Format
Lazy var variable: type = {Create variable code} ()

    • Lazy-Loading use

// The essence of lazy loading is that the closure is executed at first use, and the return value of the closure is assigned to the        property // The function of lazy is to only assign a value once        Lazy var array: [String] = {        in   return ["Ryan"  "szy""Jack"]        } ()    

Swift Fundamentals 4

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.