Swift闭包


//Closure--闭包/回调函数


//1.基本写法
let a: Int = 9

let learniOS = {
    print("学习iOS")
}
learniOS()

let learn = {(lan: String) in
    print("学习\(lan)")
}
learn("iOS")

let learn1 = {(lan: String) -> String in
    "学习\(lan)"
}
let res = learn1("iOS")
print(res)



//2.作为另外一个函数的参数
func findWork(how: ()->Void){
    print("准备找工作")
    how()
    print("找到工作了")
}
findWork(how: learniOS)



//3.trailing closure syntax--尾随闭包(闭包作为外层函数的最后一个参数时的简写)
findWork {
    print("学iOS")
}

//外层函数还有别的普通类型参数+闭包带参数时
func findWork2(a: Int, how: (String) -> Void){
    print("准备找工作2")
    how("iOS")
    print("找到工作了2")
}

findWork2(a: a, how: learn)

findWork2(a: a) { (lan) in
    print("学习\(lan)")
}


//4.$0,$1...
findWork2(a: a) {
    print("还是学习\($0)")
}


//5.闭包作为函数的返回值
func findWork3() -> (String) -> Void{
    return {
        print("不要问,问就是在学习\($0)")
    }
}

let res2 = findWork3()
res2("iOS")


//6.闭包捕获
func findWork4() -> (String) -> Void{
    var counter = 1
    
    return {
        print("不要问,问就是在学习\($0)+\(counter)")
        counter += 1
    }
}

let res3 = findWork4()
res3("iOS")
res3("iOS")
res3("iOS")