重写Swift中的func [英] Overriding func in Swift
问题描述
我正在学习Swift,并且我正在按照Paul Hegarty的一篇教程介绍如何使用波形反转表示法来构建计算器。代码如下所示:
@IBAction func操作(sender:UIButton){
let operation = sender.currentTitle !
if userIsEnteringData {
enter()
}
开关操作{
case×:performOperation {$ 0 * $ 1}
case÷: performOperation {$ 1 / $ 0}
case+:performOperation {$ 0 + $ 1}
case - :performOperation {$ 1 - $ 0}
case√:performOperation {sqrt($ 0 )}
casesin:performOperation {sin($ 0)}
casecos:performOperation {cos($ 0)}
caseπ:performOperation {$ 0 * M_PI}
default:break
}
}
func performOperation(操作:(Double,Double) - &Double; Double){
$ b (b)如果operandStack.count> = 2 {
displayValue = operation(operandStack.removeLast(),operandStack.removeLast())
enter()
}
func performOperation(操作:Double - > Double){
如果operandStack.count> = 1 {
displayValue = operation(operandStack.removeLast ())
输入()
}
}
xCode编译器不喜欢performOperation函数和报告的第二个实例它以前已经定义过。它报告的错误是:使用Objective-C选择器'performOperation:'的方法'performOperation'与之前的声明冲突,使用相同的Objective-C选择器
我的代码有什么问题?
我不知道你的类声明,但在这种情况下最可能的问题是你从 @objc
类。 Objective-C不支持方法重载,但Swift的确如此。因此,如果可以的话,您不应该继承
参考你可以阅读这篇文章
I am learning Swift and I am following a tutorial from Paul Hegarty on how to build a calculator using Polish Inverse Notation. The code looks like this:
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsEnteringData{
enter()
}
switch operation {
case "×": performOperation {$0 * $1}
case "÷": performOperation {$1 / $0}
case "+": performOperation {$0 + $1}
case "−": performOperation {$1 - $0}
case "√": performOperation {sqrt($0)}
case "sin": performOperation {sin($0)}
case "cos": performOperation {cos($0)}
case "π": performOperation{$0 * M_PI}
default: break
}
}
func performOperation (operation : ( Double, Double ) -> Double){
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
func performOperation (operation : Double -> Double){
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
The xCode compiler does not like the second instance of the performOperation function and reports that it has already been defined previously. The error it reports is:
Method 'performOperation' with Objective-C selector 'performOperation:' conflicts with previous declaration with the same Objective-C selector
What is wrong with my code?
I am not aware of your class declaration but the most possible issue in this case is that you inherit from an @objc
class. Objective-C does not support method overloading but Swift does. So either you shouldn't be inheriting from am @objc
class if you can or you can just use different method names.
For reference you can read this post
这篇关于重写Swift中的func的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!