// 1. 最简单的闭包 ()-> ()没有参数,没有返回值的函数 in 可以省略
let b1 = {
print("hello world")
}
// 执行闭包
b1()
// 2. 带参数的闭包 参数、返回值、实现代码 都写在{} 中
// { 形参列表 -> 返回值类型 实现代码 }
// 使用 in 分割定义和实现 b2 的类型: (Int)-> ()
let b2 = {(x: Int) -> () in
print(x)
}
// 执行闭包
b2(100)
// 3. 带参数/返回值的闭包
// (Int) -> Int
let b3 = {(y: Int) -> Int in
return y + 250
}
// 执行闭包
print(b3(30))
// 4.异步执行任务,获取数据,通过b1ock/闭包回调,闭包的应用场景和闭包一样
// 5 .尾随闭包 如果函数的最后一个参数是闭包,函数的参数可以提前结束,最后一个参数直接使用,包装闭包的代码
// loadData () { (result) in
// print (result)
// }
loadData { (result) in
print (result)
}
//按照函数的本身编写
loadData (completion: {(result)->0in
print (result)
})
func demo1 ({
//尾随闭包
DispatchQueue.global() .async f
//嵌套的GCD xcode不会改成尾随闭包
DispatchQueue.main.async(execute:
})
}
//尾随闭包
DispatchQueue.main.async{}
}
func loadData(completion: (result: [String]) -> ()) ->() {
//将任务添加到队列,执行任务的操作,队列的调度是以同步/异步执行任务
DispatchQueue.global().async{
print"耗时操作\ (Thread .current ()"
//休眠
Thread.sleep (forTimeInterval : 1 .0)
//获得数据
let json =["头条”,“八卦","出大事了"
//主线程更新
DispatchQueue.main. async (execute: f
print("主线程更新UI\(Thread.current())")
//回调,执行,通过参数回调
completion (result: ison)
})
}
}
//1. 使用变量记录函数
func demo (
let x: Int = sum(x: 20,y: 30)
print (nsum = 1(x)")
// 闭包:提前准备好代码,需要的时候执行,可以当做参数传递
// 定义一个常量记录函数(x:Int, y:Int) 一>Int
let f = sum
//在需要的时候执行 在oC是不能实现
print (f(x:30,y:30))
func sum (x:Int,y:Int) -> Int{
return x +y
}
网友评论