swift学习之闭包

来源:互联网 发布:sql server怎么使用 编辑:程序博客网 时间:2024/06/05 04:39

闭包和oc中的block非常相似,OC中的block非常像匿名的函数,闭包是用来定义函数(方法的)。作用:
1. block是用来保存一段代码,在需要的时候执行。复习block
2. 闭包也是用来保存一段代码,在需要的时候执行

闭包的基本格式:

in的含义是区分形参返回值和执行的代码,可以省略
无参数的闭包形式

    {        () -> ()        in        //执行的代码    }

带有参数的闭包形式:

 {        (形参:数据类型,形参:数据类型) -> 返回值        in        //执行的代码  }返回值为空的时候用“()”

block和闭包的对比:

block代码:

dispatch_async(dispatch_get_global_queue(0, 0), ^{        NSLog(@"当前的线程:%@",[NSThread currentThread]);        NSLog(@"执行超时的任务");        dispatch_async(dispatch_get_main_queue(), ^{            NSLog(@"当前的线程:%@",[NSThread currentThread]);            NSLog(@"主线称更新UI");        });    });

swift的闭包代码:

dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in            print("执行超时任务")            dispatch_async(dispatch_get_main_queue(), { () -> Void in                print("主线程跟新UI")            })        }
用闭包实现一个小例子,在UIScrollerView上添加若干UIview的例子,中间实现了两个闭包,进行传参。
import UIKitclass ViewController: UIViewController {    override func viewDidLoad() {        super.viewDidLoad()        //获取scrollView        let sv = creatScrollerView({ () -> Int in            //创建多少个UIView            return 10            }) { (index) -> UIView in                //创建View                let btn = UIButton()                btn.setTitle("标题\(index)", forState: UIControlState.Normal)                btn.frame = CGRect(x: 375*index, y: 0, width: 375, height: 444)                print(375*index);                btn.backgroundColor = UIColor(colorLiteralRed: Float(random()%10)/10.0, green: Float(random()%10)/10.0, blue: Float(random()%10)/10.0, alpha: 1)                return btn        }//        把ScrollerView添加到View上        view.addSubview(sv)    }    //带有参数的闭包    func creatScrollerView(btncount:()->Int,btnSubView:(index:Int)->UIView) -> UIScrollView    {        let sv = UIScrollView(frame: CGRect(x: 0, y: 20, width: 375, height: 444))        sv.backgroundColor = UIColor(colorLiteralRed: 0.7, green:0.2, blue: 0.3, alpha: 1);        view.addSubview(sv);        let btnCount = btncount()//执行闭包,获取数字        var width:Float = 0.0;        for i in 0..<btnCount        {            let subview = btnSubView(index: i)//执行第二个闭包获取UIView            sv.addSubview(subview)            width += Float(subview.bounds.size.width)        }        sv.contentSize = CGSize(width:CGFloat(width), height: 444)        sv.pagingEnabled = true;        return sv    }}
用闭包实现简单的小例子 ,点击屏幕更改当前界面的背景颜色
import UIKitclass ViewController: UIViewController {//    声明一个闭包    var finished:(()->())?    override func viewDidLoad() {        super.viewDidLoad()        //用weak修饰防止循环引用        weak var weakSelf = self;        //执行方法        loadTime { () -> () in            NSLog("执行更换背景颜色");            //颜色是随机值            weakSelf?.view.backgroundColor = UIColor(colorLiteralRed: Float(random()%10)/10.0, green: Float(random()%10)/10.0, blue: Float(random()%10)/10.0, alpha: 1)        }    }//    方法    func loadTime(finished:()->())    {        NSLog("执行超时操作");        self.finished = finished;    }    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {        //触发闭包        finished!()    }}
ps:

使用weak 修饰来防止闭包的循环引用问题。

0 0