About "closures" in swift

Source: Internet
Author: User

Definition of closures
    • Define a function
//: 定义一个 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
      • {Code Implementation}
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
    • A similar approach to OC
/// 类似于 OC 的解除引用func demo() { weak var weakSelf = self tools?.loadData() { print("\(weakSelf?.view)") }}
    • Recommended Methods for Swift
loadData { [weak self] in    print("\(self?.view)")}
    • It's OK
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

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.