10

I just updated from swift 1.1 to swift 1.2 and get compiler Error:

Method 'setVacation' redeclares Objective-C method 'setVacation:'

Here some code:

var vacation : Vacation?  
func setVacation(_vacation : Vacation)
{...}

But I need call setVacation

Is any suggestions how fix this?

4

3 回答 3

8

这是由 Xcode 6.3beta 发行说明中所述的更改引起的:

Swift 现在可以检测 Swift 类型系统中的重载和覆盖与通过 Objective-C 运行时看到的有效行为之间的差异。(18391046, 18383574) 例如,现在诊断出类中“property”的Objective-C setter与其扩展中的“setProperty”方法之间的以下冲突:

 class A : NSObject {
     var property: String = "Hello" // note: Objective-C method 'setProperty:’
                                    // previously declared by setter for
                                    // 'property’ here
 }
 extension A {
     func setProperty(str: String) { } // error: method ‘setProperty’
                                       // redeclares Objective-C method
                                       //'setProperty:’
 }

要解决此问题,您需要使所有方法签名都是唯一的(因为 Objective-C 不提供方法重载)

NSObject或者如果您只需要 Swift 类,请不要继承自。

于 2015-02-13T13:30:31.777 回答
4

Cappy:对于Standford问题我简单用了这个,因为看起来Xcode Beta只是说操作:(Double,Double)-> Double与操作相同:Double -> Double,我不知道是不是是不是bug...

但是下面的代码有效,但干净:(

func performOperation(r:String? = "2", 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()
    }
}
于 2015-03-05T19:33:52.453 回答
1

正如@Kirsteins 所指出的,Swift 现在可以检测 Swift 和 Obj-C 之间的冲突符号,以及会导致 Obj-C 悲伤的 swift 符号。除了给出的答案之外,您通常可以通过为其他类型指定所需的标签来避免这种情况,从而更改调用签名:

import Foundation

extension NSObject {
    func foo(d:Double, i:Int) { println("\(d), \(i)") }
    func foo(withInt d:Int, i:Int) { println("\(d), \(i)") }
}

let no = NSObject()
no.foo(withInt:1, i: 2)

除此之外,为了回答您的直接问题,您正在尝试将 Obj-C 习语应用于 Swift。你真正想要的是要么实现didSet(最有可能),要么可能set

class WhatIDidLastSummer {

    var vacation:Bool = false {
        didSet {
            // do something
        }
    }

    var staycation:Bool {
        get { return true }
        set {
            // do something
        }
    }

}
于 2015-02-20T00:13:28.603 回答