做過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的使用差不多如果你很熟悉的話那就很好了解,總的來說要使用一個閉合函數 得有
函數的參數與傳回值、函數體以及函數的執行。