[swift]-闭包的简单使用、定义

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
欢迎你们的阅读和赞赏、谢谢!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://my.oschina.net/shengbingli/blog/724994

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值