Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 1.2 not working with same function name and different parameter [duplicate]

Tags:

swift

I have 2 functions with the same name but different parameters.

The first one accepts as a parameter a function that accepts 2 doubles and returns one.

The second one accepts as a parameter a function that accept 1 double and returns one. This works in Swift 1.1, tested on Xcode 6.1.1, however in Swift 1.2, tested on Xcode 6.4 (beta), this doesn't work and gives me this error:

Method 'performOperation' with Objective-C selector 'performOperation:' conflicts with previous declaration with the same Objective-C selector

What can I do that this can work, and why that is happening? I know that I can do the square root another way then it is here,but I want to know whats the problem.

Edit

 @IBAction func operate(sender: UIButton) {
        let operation = sender.currentTitle!
        if userIsInMiddleOfTypingANumber{
            enter()
        }
        switch operation{
        case "×" : performOperation {$0 * $1}
        case "÷" : performOperation {$1 / $0}
        case "+" : performOperation {$0 + $1}
        case "−" : performOperation {$1 - $0}
        case "√" : performOperation {sqrt($0)}
        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()
        }
    }
like image 626
Stefan Scoarta Avatar asked Jun 06 '15 16:06

Stefan Scoarta


1 Answers

You cannot overload methods that Objective-C can see, because Objective-C has no overloading:

func performOperation(operation : (Double,Double) -> Double){
}
func performOperation(operation : Double -> Double) {
}

(The fact that this was allowed in Swift before Swift 1.2 was in fact a bug; Swift 1.2 closed the loophole and fixed the bug.)

Simple solution: hide these methods from Objective-C. For example, declare them both private.

More tricky solution: change the name by which Objective-C sees one of them. For example:

func performOperation(operation : (Double,Double) -> Double){
}
@objc(performOperation2:) func performOperation(operation : Double -> Double) {
}

Or, new in Swift 2.0, you can hide one or both of them from Objective-C without going so far as to make it private:

@nonobjc func performOperation(operation : (Double,Double) -> Double){
}
func performOperation(operation : Double -> Double) {
}
like image 155
matt Avatar answered Nov 12 '22 09:11

matt