加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 1.2不使用相同的函数名和不同的参数

发布时间:2020-12-14 05:40:33 所属栏目:百科 来源:网络整理
导读:参见英文答案 Compiler error: Method with Objective-C selector conflicts with previous declaration with the same Objective-C selector6个 我有2个具有相同名称但不同参数的函数. 第一个接受一个接受2个双精度并返回1的函数作为参数. 第二个接受一个接
参见英文答案 > Compiler error: Method with Objective-C selector conflicts with previous declaration with the same Objective-C selector6个
我有2个具有相同名称但不同参数的函数.

第一个接受一个接受2个双精度并返回1的函数作为参数.

第二个接受一个接受1 double并返回1的函数作为参数.这适用于在Xcode 6.1.1上测试的Swift 1.1,但是在Swift 1.2中,在Xcode 6.4(beta)上测试过,这不起作用并且给我这个错误:

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

我能做些什么才能发挥作用,为什么会这样呢?
我知道我可以用另一种方式做平方根然后就在这里,但我想知道问题是什么.

编辑

@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()
        }
    }
你不能重载Objective-C可以看到的方法,因为Objective-C没有重载:
func performOperation(operation : (Double,Double) -> Double){
}
func performOperation(operation : Double -> Double) {
}

(Swift 1.2之前在Swift中允许的事实实际上是一个bug; Swift 1.2关闭了漏洞并修复了bug.)

简单的解决方案:从Objective-C中隐藏这些方法.例如,声明它们都是私有的.

更棘手的解决方案:更改Objective-C看到其中一个的名称.例如:

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

或者,Swift 2.0中的新功能,您可以从Objective-C中隐藏其中一个或两个,而不会使其变为私有:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读