闭包,协议delegate
1.定义
//1.闭包表达式语法 { (parameters) -> returnType in statements } let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] var reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 }) //2.单表达式闭包隐式返回 //单行表达式闭包可以通过省略 return 关键字来隐式返回单行表达式的结果 reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } ) //3.参数名称缩写 //可以直接通过 $0 , $1 , $2 来顺序调用闭包的参数,以 此类推 reversedNames = names.sorted(by: { $0 > $1 } ) //例子中,$0和$1表示闭包中第一个和第二个 String 类型的参数。
2.尾随闭包
//1.闭包表达式语法 func someFunctionThatTakesAClosure(closure: () -> Void) { // 函数体部分 } // 以下是不使用尾随闭包进行函数调用 someFunctionThatTakesAClosure(closure: { // 闭包主体部分 }) // 以下是使用尾随闭包进行函数调用 someFunctionThatTakesAClosure() { // 闭包主体部分 } someFunctionThatTakesAClosure { } let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] let k = names.map { (a) -> Int in if a == "Alex" { return 1 } else { return 0 } } print(k)
3.逃逸闭包
var completionHandlers: [() -> Void] = [] func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) { completionHandlers.append(completionHandler) }
4.自动闭包
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] print(customersInLine.count) // 打印出 "5" let customerProvider = { customersInLine.remove(at: 0) } print(customersInLine.count) // 打印出 "5" print("Now serving \(customerProvider())!") // Prints "Now serving Chris!" print(customersInLine.count) // 打印出 "4"
5.别名
typealias AddBlock = (Int, Int) -> (Int) let Add:AddBlock = { (c,d) in return c + d } let Result = Add(100,150) print("Result = \(Result)")
使用实例
6.回调,代替delegate,注意:循环引用,类似block,(只要控制器vc直接或间接拥有闭包,并在闭包中使用self,就会出现循环引用)
1.自定义个view ,LyContentView class LyContentView: UIView { //代替delegate,的闭包 var tapClick : (_ tap : UITapGestureRecognizer)->() = {_ in } override init(frame: CGRect) { super.init(frame: .zero) //操作在这实现 let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapClick(_:))) addGestureRecognizer(tap) } @objc fileprivate func tapClick(_ tap : UITapGestureRecognizer) { print("点击了") self.tapClick(tap) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } 2.在控制器中使用 contentView.tapClick = { tap in print("点击了view") }
7.解决闭包循环引用
// weak var weakSelf = self; // [weak self] () -> () in // [unowned self] () -> () in 注意:这种不推荐使用 httpTool.loadRequest { [unowned self] () -> () in self.view.backgroundColor = UIColor.redColor() print("回到主线程", NSThread.currentThread()); }
8.封装网络请求
class func post(url : String , parameters : [String : String]? , header : [String : String]? , success : @escaping (_ response : [String : AnyObject])->() , failure : @escaping (_ error : Error)->()) { Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header).responseJSON { (json) in switch json.result { case .success(let value): success(value as! [String : AnyObject]) case .failure(let error): failure(error) } } }
9.懒加载
fileprivate lazy var tableView : UITableView = { let tableView = UITableView() tableView.backgroundColor = UIColor.white tableView.tableFooterView = UIView() return tableView }()
10.协议/代理,delegate
@objc protocol BaseModelDelegate : NSObjectProtocol { //非必须实现的协议 @objc optional func arrayContainModelClass() -> ([String : Any]) @objc optional func dictContainModelClass() -> ([String : Any]) //必须实现的协议 func BaseModelKey() }