我刚刚从 swift 1.1 更新到 swift 1.2 并得到编译器错误:
Method 'setVacation' redeclares Objective-C method 'setVacation:'
这里是一些代码:
var vacation : Vacation?
func setVacation(_vacation : Vacation)
{...}
但我需要调用setVacation
有什么解决办法的建议吗?
最佳答案
这是由 Xcode 6.3beta 发行说明中所述的更改引起的:
Swift now detects discrepancies between overloading and overriding in the Swift type system and the effective behavior seen via the Objective-C runtime. (18391046, 18383574) For example, the following conflict between the Objective-C setter for “property” in a class and the method “setProperty” in its extension is now diagnosed:
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 不提供方法重载)
或者如果您只需要 Swift 类,则不要继承 NSObject
。
关于Swift 1.2 重新声明 Objective-C 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28500486/