[英]Issue with conforming to Objective-C protocol from Swift NSObject subclass
This piece of code works absolutely fine in Swift 1.1 这段代码在Swift 1.1中可以正常工作
// Obj-C
@import Foundation;
@protocol HashableObject <NSObject>
- (NSUInteger)hash;
@end
// Swift
import Foundation
@objc class Object: NSObject, HashableObject {
func hash() -> UInt {
return 0
}
}
However, in latest Swift 1.2 and XCode 6.3beta2 the compiler complains that Method 'hash()' overrides Objective-C method 'hash' from superclass 'NSObject'
但是,在最新的Swift 1.2和XCode 6.3beta2中,编译器抱怨
Method 'hash()' overrides Objective-C method 'hash' from superclass 'NSObject'
Is that a bug, or something else has fundamentally changed and the code is wrong? 那是一个错误,还是其他根本改变了,代码是错误的? Are there any workarounds to this?
有什么解决方法吗? I have numerous things in my code that need to conform to certain protocols from Objective-C libraries and this essentially breaks everything with no apparent solution other than wait for the next Swift release.
我的代码中有很多东西需要符合Objective-C库中的某些协议,这实质上是在没有其他解决方案的情况下破坏一切,除了等待下一个Swift版本。
NSObject
already has hash
property : NSObject
已经具有hash
属性 :
protocol NSObjectProtocol {
var hash: Int { get }
And, Swift 1.2 detects these erroneous overrides. 而且,Swift 1.2检测到这些错误的覆盖。 From the release notes:
从发行说明中:
Swift now detects discrepancies between overloading and overriding in the Swift type system and the effective behavior seen via the Objective-C runtime.
Swift现在可以检测Swift类型系统中的重载和重写与通过Objective-C运行时看到的有效行为之间的差异。 (18391046, 18383574)
(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:
例如,现在诊断出类中“属性”的Objective-C设置器与其扩展名中的方法“ 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:' }
In Swift 1.2 (Xcode 6.3 beta 2) you can override the hash
property of NSObject
as a computed property: 在Swift 1.2(Xcode 6.3 beta 2)中,您可以覆盖
NSObject
的hash
属性作为计算属性:
class Object: NSObject {
override var hash: Int {
return 0
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.