swift3.0 之 闭包(Closure)

2017-05-26  本文已影响0人  Just丶Go

swift闭包 格式
(parameters) ->(return type) = { }
parameters -> 参数
return type -> 返回值的类型
{} 内的内容 下面详细讲解

  1. parameters 详解
    这个 参数 可以是常规数据类型, 也可以是元组
  2. return type 返回的数据类型
  3. {} 里的内容 根据 parameters 内的内容变化
    1. 有参数,有返回值 {a , b ,c in return d}
    2. 有参数,无返回值 {a, b in }
    3. 无参数 有返回值 { return}
    4. 无参数,无返回值 { }
      下面是使用实例
      第二个 界面 push之后的 用于闭包逆传值

import UIKit

class SecondController: UIViewController {
    /// 闭包声明 一 : 很笨
    var returnResultClosure: (String) -> (Void) = {
        string in
    }
    var name = String()

    /// 闭包声明 二 : 比较好
    var block: ((Int,Int) ->Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.orange
        // Do any additional setup after loading the view.
        
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        returnResultClosure("几点啦,大哥")
        block!(1, 5)
        self.navigationController?.popViewController(animated: true)
    }
}

// 第一个控制器 接收 逆传返回的值

import UIKit

class ViewController: UIViewController {
    var integer: Int = Int()
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.title = "首页"
        self.view.backgroundColor = randColor()
       
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    {
        self.view.backgroundColor = randColor()
        // Do any additional setup after loading the view, typically from a nib.
        print("屏幕点击")
        let vc = SecondController()
        vc.name = "alpha go"
        vc.returnResultClosure = {
            result in
            print(result)
        }
        vc.block = {
            a, b in
            print(a, b)
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }

}
上一篇 下一篇

猜你喜欢

热点阅读