Swift 参数闭包(Closure)

前言

swift的closure类似于oc的block
closure闭包可以方法、参数、属性等形式存在,下面主要讲述参数和属性闭包

Closure闭包

  • non-escaping Closures
Swift 参数闭包(Closure)_第1张图片
closure-noescape.png

non-escaping闭包,在function return后,闭包也运行完成,
如同Closures、function在都在单线程上完成。

  • escaping Closures
Swift 参数闭包(Closure)_第2张图片
closure-escape (1).png

escaping Closures闭包,在function return后,闭包的状态不一定会完成,而且闭包的调用时机、完成时间也不可控。
跟oc的block有点相似,都可异步回调!
【oc的block内存管理方面会比较特殊,swift的Closures是否也会有内存管理问题?答案是:没有,变量在Closures改变,而引用计数并没有增加】

ps:
swift1.0、2.0闭包参数都是默认escaping Closures
swift3.0之后闭包参数默认non-escaping Closures
在生命周期来说,还是non-escaping Closures比较安全,escaping Closures可做异步优化等操作

参数闭包

import UIKit

class AFN_Hepler_Z: NSObject {

    static func postDataByString(urlSting: String, bodyDic: NSDictionary!, succeed: @escaping (_ responeObject: NSString) -> (), fail: @escaping (_ error: AnyObject) -> ()){
        
    }   
}

调用

let dict_parmas:NSDictionary =  ["code" : "index",
                                         "community_id":17,
                                         "province_id":14791,
                                         "city_id":15020,
                                         "region_id":18584]
        
        AFN_Hepler_Z.postDataByString(urlSting: url_goods, bodyDic: dict_parmas, succeed: { (responeObject:NSString) in
            
            print("succeed closure")
        }) { (error:AnyObject) in
            print(error)
        }

属性闭包

在UITableViewCell中嵌套一个UICollectionView,tableViewCell添加一个属性闭包,在tableViewCell里面的CollectionView点击事件中,回调tableViewCell的属性闭包

  • step1:
    tableViewCell中书写属性闭包
var selectClosure:((NSInteger)->())? = nil

实现CollectionView代理方法,CollectionView点击回调闭包

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if (selectClosure != nil) {
            selectClosure!(indexPath.item)
        }
    }

UITableView代理方法中,设置回调操作

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  
        let cell_scene=tableView.dequeueReusableCell(withIdentifier: "SceneCell") as! SceneCell
        cell_scene.backgroundColor=UIColor.clear
        //设置回调操作
        cell_scene.selectClosure={(index:NSInteger) in
            //点击CollectionViewCell回调此方法
            print(index)
        }
        return cell_scene
    }

你可能感兴趣的:(Swift 参数闭包(Closure))