Swift3.0 function closure and OC Block

Source: Internet
Author: User
Tags closure

Just contact Swift, if there is a wrong point, please correct me. Reprint please indicate the source

    • Define a basic function in Swift
// defines a function that receives a string that returns the value of a string type, func test (name:string), string        {return ("  output \ (name)    }// general form return  type {        function Body    }

  • The similarity between the basic closure function in Swift and the block in OC
  • With closed package
    //This is the block in OC.void(^test) (NSString *) =^ (NSString *name) {NSLog (@"%@", name);    }; Test (@"Test");//corresponding to Swift with the reference closureLet Test={(_ Name:string) ()inch  //In the back is the function that is processed after the callback, equivalent to the {} after the blockprint (name)} Test ("Test")//General Form{(parameters)ReturnTypeinchCode}

Here the effect of the underline _ is used to ignore the external parameter name, specifically refer to this article http://www.cnblogs.com/bhlsheji/p/4746072.html

    • function definition with block parameter in OC
-(void) LoadData: (  void(^) (void)) completetion{    completetion ();}

    • function definition with closure parameters in Swift
Func LoadData (completetion: ()), () {       completetion ()    }//

    • For a more common example, network data acquisition
//block transfer value in OC-(void) LoadData: (void(^) (Nsarray *)) completetion{//Here for the time being, ignoring the thread, simple processing, focusing on swift closureNSLog (@"time-consuming Operation"); Sleep (2);//Simulating network requestsNsarray*[email protected][@"1",@"2"]; NSLog (@"Main thread Callback"); Completetion (arr); //returns the data obtainedcall: [Self loaddata:^ (Nsarray *callBack) {NSLog (@"%@,%@", callback[0],callback[1]); }]; output: .-Geneva- A  -: -:45.273tessst[3642:187462] Time-consuming Operation .-Geneva- A  -: -:47.345tessst[3642:187462] Main thread update .-Geneva- A  -: -:47.346tessst[3642:187462]1,2//closed packet transfer value in SwiftFunc loaddate (Completion: @escaping (_ Result: [String]), () {//here is a very important parameter @escaping, escape closure//simply put, the closure is called before the end of the function, which is the non-escape closure, where the call exceeds the range of the function, called escape closure .//The general network request is the request after a period of time the closure is executed, so all are escape closures. //all closed Baudumo in Swift3.0 are considered non-escape closures, so they need to be modified with @escapingDispatchqueue.Global(). async {Print ("time consuming Operation \ (thread.current)") Thread.Sleep (fortimeinterval:2) Let JSON=["1","2"] DispatchQueue.main.async {print ("main thread update \ (thread.current)") Completion (JSON)//function after the execution of two seconds, the main line friend callback data, beyond the scope of the function, here is the escape closure, if not @escaping, the compiler is compiled but}}} Main function call Loaddate:loaddate {(callBack)inchPrint ("\ (callBack)")} Output value time consuming operation<nsthread:0x608000069140>{number =1, name =main} main thread update<nsthread:0x608000069140>{number =1, name =main}1,2

    • There are often circular references in blocks, as in closures, and there are two common ways to solve them.
//First KindWeak Var weakwelf= Self//the way OC is applied (__weak typedef (WEAKSELF) =self).//It is important to note that you cannot use let because self may release a pointer to nil, which is equivalent to a mutable value//can I use the option to send a message? Unpacking, No! Pringt ("weakself?. View") No"weakself!. View"//because forcing the unpacking will crash once Weakself=nil//second, at the time of the call//[Weak self] identifies that all self in {} is a weak referenceloaddate {[Weak self]inchPrint ( self?. View)}

Continue to be more ...

Swift3.0 function closure and OC Block

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.