您的位置:首页 > 移动开发 > Swift

swift闭包纯代码

2016-07-29 10:50 537 查看
做过swift开发的肯定要用到闭包,swift中的闭包就相当于OC里面的block都是用于回调。

举个简单的例子,返回两个参数的和:

第一种 常规做法

//返回两个数的和
func sum(numberOne number1:Int,numberTwo number2:Int)->Int
{
return (number1 + number2)
}

let sumTwoNumber = sum(numberOne: 1, numberTwo: 2)


第二种 使用闭包

var myCloure0:((Int,Int)->Int)?            //声明一个闭包函数
typealias MyCloureType = (Int,Int) -> Int  //类型取一个别名
var myCloure:MyCloureType?

//参数列表和真正的函数体之间使用关键字in来分割
myCloure0 = {
(num1:Int,num2:Int) -> Int in
return num1+num2
}
myCloure = {
(num1:Int,num2:Int) -> Int in
return num1+num2
}
//执行闭包函数
let sumInt:Int =  myCloure0!(10,10)
let sumInt1:Int =  myCloure!(20,20)
print("sumInt = \(sumInt) sumInt1 = \(sumInt1)")
打印:
sumInt = 20 sumInt1 = 40

我们发现闭包用起来也非常简单,下面来看看闭包的回调传值:
先定义两个控制器  FirstViewController SecondViewController
first控制器:

class FirstViewController: UIViewController {

var fisrtBtn:UIButton = {
let button:UIButton = UIButton()
button.backgroundColor = UIColor.redColor()
button.setTitle("Go SecondViewController", forState: .Normal)
button.layer.masksToBounds = true
return button
}()

var secondLabel:UILabel = {
let label:UILabel = UILabel()
label.backgroundColor = UIColor.greenColor()
label.text = "显示Second中输入的值"
label.font = UIFont.systemFontOfSize(13.0)
return label
}()

override func viewDidLoad() {
super.viewDidLoad()

fisrtBtn.frame = CGRectMake(50, 50, 200, 40)
secondLabel.frame = CGRectMake(50, 100, 200, 40)
fisrtBtn.addTarget(self, action:#selector(FirstViewController.fisrtBtnClick(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(fisrtBtn)
self.view.addSubview(secondLabel)
}

func fisrtBtnClick(sender:UIButton)
{
let secondVc = SecondViewController()
//实现回调,接收回调过来的值
secondVc.setBackMyClosure { (inputText:String) in
self.secondLabel.text = inputText
}

}
}
Second控制器:

typealias InputClosureType = (String)->Void   //闭包类型的函数 参数为string 返回值void

class SecondViewController: UIViewController {

var backBtn:UIButton = {
let button:UIButton = UIButton()
button.backgroundColor = UIColor.redColor()
button.setTitle("back", forState: .Normal)
button.layer.masksToBounds = true
return button
}()
var backClosure:InputClosureType?        //声明闭包函数
override func viewDidLoad() {
super.viewDidLoad()
backBtn.frame = CGRectMake(100, 100, 100, 100)
backBtn.addTarget(self, action: #selector(SecondViewController.tapBackButton(_:)), forControlEvents:.TouchUpOutside)
self.view.addSubview(backBtn)
}
//闭包变量赋值
func setBackMyClosure(tempClosure:InputClosureType)
{
backClosure = tempClosure
}

func tapBackButton(sender:UIButton)
{
if(backClosure != nil)
{
let tempString:String? = "peng xun xun"
if(tempString != nil)
{
backClosure!(tempString!)  //执行闭包
}
}
self.navigationController?.popViewControllerAnimated(true)
}

}


这就是闭包传值基本上跟OC block的使用差不多如果你很熟悉的话那就很好理解,总的来说要使用一个闭合函数 得有

函数的参数与返回值、函数体以及函数的执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift 闭包