函數(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è)塊壹无,需要改變書寫的語法
@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)一步將塊簡化
@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)一步簡化
@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ù)沒有命名岖是,默認(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ù)沒有其他參數(shù),則括號(hào)也可以省略陆错,得到最終精簡版
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation{$0 * $1}
default:break
}
}