////Viewcontroller.swift//definition and use of closures////Created by think Peng on 16/9/17.//copyright©2016 of the year. All rights reserved.//Import UIKitclassViewcontroller:uiviewcontroller {Overridefunc viewdidload () {super.viewdidload ()//1>: The simplest closure (), no parameters, no return value if there is no parameter, no return value, in can be omittedLet B1 ={print ("Hello SiSi") } //Execute ClosuresB1 ()//2. Closure parameters with parameters, return value, implementation code is written in {}//{formal parameter list-> return value type//Implementation Code}//define and implement the type of B2 using the in Split: (INT), ()Let B2 = {(X:int), ()inchprint (x)}//Execute ClosuresB2 ( -) //3. Closures with parameters/return values//int (int)Let B3 = {(Y:int)->intinch returnY + - } //Closure callsPrint (B3 ( -)) //4. Execute tasks asynchronously, get data, pass block/closure callback, closure application scenario and closure//5. Trailing closure If the last parameter of the function is a closure, the function's parameters can be terminated prematurely, and the last parameter is used to wrap the closure code directly with {} /*LoadData () {(result) in print (result)}*/LoadData {(result)inchprint (Result)}//written according to the function itselfLoadData (completion: {result)inchprint (Result)}) } func Demo1 () {//trailing closuresDispatchqueue.Global(). async {//nested GCD Xcode does not change to a trailing closureDispatchQueue.main.async (execute: {})}//trailing closuresDispatchQueue.main.async {}} func LoadData (completion: (Result: [String]) , ()) () { //add a task to a queue, perform a task, and schedule the queue to perform tasks synchronously/asynchronouslyDispatchqueue.Global(). async{Print ("time-consuming operation \ (Thread. Current ())") //HibernateThread.Sleep (fortimeinterval:1.0) //Get the dataLet JSON = ["Headlines","Gossip","something big."] //Main thread UpdateDispatchQueue.main.async (execute: {print ("main thread Update ui\ (Thread.current ())") //callback, execution, callback by parametercompletion (Result:json)}) } } //1. Using variables to record functionsFunc Demo () {Let x:int= SUM (x: -Y: -) Print ("sum = \ (x)") //closures: Prepare the code in advance, execute it when needed, and pass it as a parameter//defines a constant record function (X:int, y:int), IntLet F =sum//execution at OC is not achievable when neededPrint (f (x: -Y: -) }} func sum (x:int,y:int)-Int {returnX +y}}
Definition and use of Swift 3.0 closures