闭包
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let f = sum //f把函数指针记录下来
print(f(20,40))
//最简单的闭包
let b1 = {
print("干掉他们")
}
b1()
//闭包的格式 {形参列表 ->返回值类型 in 实现代码}
let b2 = {
(x:String) ->() in print(x)
}
b2("String")
//带参数带返回值的闭包
let b3 = {
(x:Int)->Int in return x + 3
}
b3(4)
}
func sum(x:Int,y:Int) -> Int {
return x + y
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//普通调用
myFunc(strP: "hello", closureP: {
(string) in print(string)
})
//尾随闭包
myFunc(strP: "hello") {
(string) in print(string)
}
testEscaping {
[unowned self] ()-> Void in
self.x = 100
}
print(x)
callBackArray.first?() //修改了x
print(x)
}
func myFunc(strP:String,closureP:(String)->Void) -> Void {
closureP(strP)
}
var x = 10
var callBackArray:[()->Void] = [] //定义数组 数组的元素都是闭包类型的
// @escaping 允许逃逸出函数
//逃逸闭包的方法
func testEscaping(callBack:@escaping ()->Void) {
callBackArray.append(callBack)
}
}