swift继承自Objective-C基类时重载方法报错的问题

今天在学斯坦福的ios公开课时,使用Demo源码编译报错

@IBAction func operate(sender: UIButton) {
        let operate = sender.currentTitle!
        switch operate{
        case "+":performOprate{ $0 + $1 }
        case "−":performOprate{ $0 - $1 }
        case "×":performOprate{ $0 * $1 }
        case "÷":performOprate{ $0 / $1 }
        case "√":performOprate{ sqrt($0)}
        default:break
        }

    }
    func performOprate(operation:(Double, Double)->Double){ if(operandStack.count>=2){ displayValue = operation(operandStack.removeLast(),operandStack.removeLast()); enter() } } func performOprate(operation: Double -> Double){ if(operandStack.count>=1){ displayValue = operation(operandStack.removeLast()); enter() } }

错误:Method ‘performOprate’ with Objective-C selector ‘performOprate:’ conflicts with previous declaration with the same Objective-C selector

上网查找得到的答案:
http://stackoverflow.com/questions/29457720/compiler-error-method-with-objective-c-selector-conflicts-with-previous-declara
The problem is UIViewController is an @objc class. When inheriting from UIViewController, BugViewController is also a @objc class.

This means it must conform to the rules of Objective-C selectors (the name of a method). The methods func perform(operation: (Double) -> Double) and func perform(operation: (Double, Double) -> Double) both have the same selector @selector(perform:). This is not allowed.

To resolve this, use different names: like func perform1(operation: (Double) -> Double) and func perform2(operation: (Double, Double) -> Double).

I think the best way to handle this is to give your perform() methods more descriptive names. What do these methods do? How do they change the state of the view controller? Look at the other UIViewController methods to get a feel for the style of method naming, or read Method Names Should Be Expressive and Unique Within a Class
因为继承自UIViewController,而UIViewController又继承自oc的NSObject,在swift中被修饰成@obj class,所以需要遵守oc的selector,在oc中不支持方法重载,所以有两个解决方案:1.换方法名字,2.不继承自OC的类
修改如下:

@IBAction func operate(sender: UIButton) {
        let operate = sender.currentTitle!
        switch operate{
        case "+":performOprate{ $0 + $1 }
        case "−":performOprate{ $0 - $1 }
        case "×":performOprate{ $0 * $1 }
        case "÷":performOprate{ $0 / $1 }
        case "√":performOprate_{ sqrt($0)}
        default:break
        }

    }
    func performOprate(operation:(Double, Double)->Double){ if(operandStack.count>=2){ displayValue = operation(operandStack.removeLast(),operandStack.removeLast()); enter() } } //更换方法的名字 func performOprate_(operation: Double -> Double){ if(operandStack.count>=1){ displayValue = operation(operandStack.removeLast()); enter() } }

你可能感兴趣的:(swift)