//: Playground - noun: a place where people can play
//Swift 闭包
//定义
//无参数无返回值的闭包
var completionCallback :(()->())?
//无参数有返回值的闭包
var completionHandler:(()->Int)?
//有参数无返回值的闭包
var finishCallBack :((Int) ->())?
//有参数有返回值的闭包
var successHandler :((Int) ->(Int))?
//无参数无返回值的闭包
completionCallback = { () in
print("无参数无返回值的闭包执行了");
};
completionCallback!();
//无参数有返回值的闭包
completionHandler = { ()in
print("闭包被调用了");
return 20;
};
let a = completionHandler!();
print(" a:\(a)")
//有参数无返回值的闭包
finishCallBack = { (a) in
print("有参数无返回值的闭包 a:\(a)")
};
finishCallBack!(10);
//有参数有返回值的闭包
successHandler = {(a) ->(Int)in
print("有参数有返回值 a:\(a)");
return 10;
};
let result = successHandler!(20);
print(result);
// 闭包作为参数传递的情况
func successFunction(success:@escaping (Int)->(Int)) -> () {
successHandler = success;
let result = success(10);
print("successFunction result :::\(result)")
}
func doSomthing(finish:@escaping (Int)->()) -> () {
finishCallBack = finish;
finish(10);
}
func loadNetWorkData(completion:@escaping ()->Int) -> () {
completionHandler = completion;
let a = completion();
print("a:\(a)");
}
网友评论