Definition of closures
//: 定义一个 sum 函数func sum(num1 num1: Int, num2: Int) -> Int { return num1 + num2}sum(num1: 10, num2: 30)//: 在 Swift 中函数本身就可以当作参数被定义和传递let mySum = sumlet result = mySum(num1: 20, num2: 30)
- Define a closure
- Closed package = {(row parameter), return value in//code implementation}
inFor distinguishing function definitions from code implementations
//: 闭包 = { (行参) -> 返回值 in // 代码实现 }let sumFunc = { (num1 x: Int, num2 y: Int) -> Int in return x + y}sumFunc(num1: 10, num2: 20)
- The simplest closure, if there is no parameter/return value,
参数/返回值/in all can be omitted
let demoFunc = { print("hello")}
Basic use of GCD async
- Simulate loads data in the background line
func loadData() { dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in print("耗时操作 \(NSThread .currentThread())") })}
- Trailing closures, if the closure is the last parameter, you can use the following notation
- Note
} the position of the upper and lower sections of the code
func loadData() { dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in print("耗时操作 \(NSThread .currentThread())") }}
- Shorthand for closures, if there are no parameters and return values in the closure, you can omit the
func loadData() { dispatch_async(dispatch_get_global_queue(0, 0)) { print("耗时操作 \(NSThread .currentThread())") }}
Custom closure parameters to implement the main thread callback
- Add a closure with no parameters, no return value
OverrideFuncViewdidload () {super.viewdidload () LoadData { print ( "completion callback")}} //MARK:-Custom closure parameters func loaddata (finished: () 0, 0)) {print ( "time-consuming operation \ ( Nsthread.currentthread ()) ") Dispatch_sync (Dispatch_get_main_queue ()) {print ( "main thread callback \ (Nsthread.currentthread ())") // Execute callback finished ()}}
- Adding callback Parameters
OverrideFuncViewdidload() {Super.viewdidload () loadData4 {(HTML), ()in print (HTML)}} / //Load data// completion callback-Incoming callback closure, receive the result of asynchronous execution func loadData4(Finished: (html:string), ()) {Dispat Ch_async (Dispatch_get_global_queue (0, 0)) { print ("Load data \ (Nsthread.currentthread ())") Dispatch_sync (Dispatch_get_main_queue ()) { print ("completion callback \ (Nsthread.currentthread ())") Finished (HTML: "
Circular references
- Build
NetworkTools Objects
class NetworkTools: NSObject { /// 加载数据 /// /// - parameter finished: 完成回调 func loadData(finished: () -> ()) { print("开始加载数据...") // ... finished() } deinit { print("网络工具 88") }}
- Instantiate
NetworkTools and load data
class Viewcontroller: uiviewcontroller {var tools: networktools? override func viewdidload () {super.viewDidLoad ( ) tools = networktools () tools?. LoadData () {print ( "Come here \ ( Span class= "Hljs-keyword" >self.view)}} ///similar to Dealloc in OC, note that this function has no () deinit {print (" Controller ")}}
The run does not form a circular reference because the reference to self is released when the LoadData finishes executing
- Modify
NetworkTools , define callback closure properties
///completion callback property var Finishedcallback: (()-())? ///load data //////-parameter finished: completion callback func loaddata ( Finished: () ()) { Self.finishedcallback = finished print ( "Start loading data ...") //... working ()}func working () {Finishedcallback? ()} deinit {print ( "network tool 88")}
To run the test, a circular reference will appear
To dismiss a circular reference
/// 类似于 OC 的解除引用func demo() { weak var weakSelf = self tools?.loadData() { print("\(weakSelf?.view)") }}
- Recommended Methods for Swift
loadData { [weak self] in print("\(self?.view)")}
loadData { [unowned self] in print("\(self.view)")}
Closure (Block) Circular Reference Summary
Swift
[weak self]
selfis optional, if self is already disposed;nil
[unowned self]
selfis not an option, if self is already disposed, the野指针访问
ObjC
__weak typeof(self) weakSelf;
- If
self it has been released;nil
__unsafe_unretained typeof(self) weakSelf;
- If
self it has been released, a wild pointer access
About "closures" in swift