//
// 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
})
}
}
}
闭包的基本概念
最新推荐文章于 2023-05-03 16:24:48 发布