闭包的基本概念

//
//  ViewController.swift


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        /*
         闭包和OC中的Block非常相似
         OC中的Block类似匿名函数
         闭包是用来定义函数

         作用:Block是用于保存一段代码,在需要的时候执行
                闭包也是。
         做一些耗时操作经常用到
         */

        /*
         闭包的基本格式:

         {
            () -> ()
            in
            //code...
         }
         */

        /*
         闭包的几种格式:
         1.将闭包通过实参传递给函数
         */
        loadData(10,finished: {() -> () in
                print("被回调了")
            }
        )

        //2.如果闭包是函数的最后一个参数,那么闭包可以写在()后面
        loadData(10){() -> () in
            print("被回调了")
        }

        // 3.如果函数只接收一个参数,并且这个参数是闭包,那么()可以省略
        say{() ->() in
            print("hello")
        }

        /*
         闭包的简写:
         如果闭包没有参数也没有返回值,那么in之前的东西都可以不写,包括in
         */
    }

    func say(finished: () -> ())
    {
        //
    }

    // 接收一个闭包,加载数据
    func loadData(num:Int, finished:() -> ())
    {
        // 执行耗时操作

        // 执行闭包,回调通知调用者
        finished();
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // Swift中dispatch_async回调的是一个闭包
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            print(NSThread.currentThread())
            // 执行耗时操作

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                print(NSThread.currentThread())
                // 主线程更新UI
            })
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值