函数作为参数
以乘法为例
1.multiply为定义的方法,作为参数传入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函数作为一个块,需要改变书写的语法
@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.因为swift可以做到类型推断,因此可以进一步将块简化
@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方法知道调用的方法将会返回一个Double值,而且,此处仅且返回一个值,因此可以进一步简化
@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 不强制要求给参数命名,如果参数没有命名,默认为$0,$1...以此类推,因此,参数名也可以省略
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation({$0 * $1})
default:break
}
}
6.若此参数为函数的最后一个参数,且为operation类型,则可以将此参数移到括号的外面,若之前有其他参数,依然可以放在括号内,若此时除了此参数没有其他参数,则括号也可以省略,得到最终精简版
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation{
case "*": performOperation{$0 * $1}
default:break
}
}