函數(shù)作為參數(shù)
以乘法為例
1.multiply為定義的方法,作為參數(shù)傳入performOperation
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation(multiply)
default:break
}
}
func multiply(opt1:Double,opt2:Double)->Double{
return opt1 * opt2
}
func performOperation(operation:(Double,Double)->Double){
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
2.把multiply函數(shù)作為一個(gè)塊,需要改變書(shū)寫(xiě)的語(yǔ)法
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation({(opt1:Double,opt2:Double)->Double in
return opt1 * opt2
})
default:break
}
}
3.因?yàn)閟wift可以做到類型推斷,因此可以進(jìn)一步將塊簡(jiǎn)化
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation({(opt1,opt2) in
return opt1 * opt2
})
default:break
}
}
4.由于performOperation方法知道調(diào)用的方法將會(huì)返回一個(gè)Double值,而且,此處僅且返回一個(gè)值,因此可以進(jìn)一步簡(jiǎn)化
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation({(opt1,opt2) in opt1 * opt2})
default:break
}
}
5.Swift 不強(qiáng)制要求給參數(shù)命名,如果參數(shù)沒(méi)有命名,默認(rèn)為$0,$1...以此類推,因此,參數(shù)名也可以省略
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation({$0 * $1})
default:break
}
}
6.若此參數(shù)為函數(shù)的最后一個(gè)參數(shù),且為operation類型,則可以將此參數(shù)移到括號(hào)的外面,若之前有其他參數(shù),依然可以放在括號(hào)內(nèi),若此時(shí)除了此參數(shù)沒(méi)有其他參數(shù),則括號(hào)也可以省略,得到最終精簡(jiǎn)版
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation{$0 * $1}
default:break
}
}