1:swift中闭包和oc中block一样,都是常用于回调,闭包也是一种特殊函数
2:代码演示:
import UIKit
class HttpTools: NSObject {
// 闭包的类型:(参数列表) -> (返回值类型)
func loadData(callBack : (jsonData : String) -> ()) {
dispatch_async(dispatch_get_global_queue(0, 0)) {
print("发送网络请求\(NSThread.currentThread())")
dispatch_sync(dispatch_get_main_queue(), {
print("获取到数据,并且进行回调:\(NSThread.currentThread())")
callBack(jsonData: "jsonData数据===================")
})
}
}
}
import UIKit
class ViewController: UIViewController {
// 创建属性的同时初始化对象
var tools : HttpTools = HttpTools()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("-----");
tools.loadData { (jsonData) in
print("拿到了json数据了:\(jsonData)")
}
}
}
3:闭包的定义格式: (参数列表) -> (返回值类型)
如:callBalk : (jsonData : String) -> ()
4:swift中:标志符在前 : 类型 && OC中:类型在前 * 标志符名字
意见反馈邮件:1415429879@qq.com
欢迎你们的阅读和赞赏、谢谢!