gpt4 book ai didi

ios - 符合 Swift NSObject 子类的 Objective-C 协议(protocol)的问题

转载 作者:搜寻专家 更新时间:2023-11-01 06:23:36 25 4
gpt4 key购买 nike

这段代码在 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
}
}

然而,在最新的 Swift 1.2 和 XCode 6.3beta2 中,编译器提示 Method 'hash()' overrides Objective-C method 'hash' from superclass 'NSObject'

这是一个错误,还是其他什么从根本上改变了,代码是错误的?有什么解决方法吗?我的代码中有很多东西需要符合 Objective-C 库的某些协议(protocol),这基本上破坏了一切,除了等待下一个 Swift 版本之外没有明显的解决方案。

最佳答案

NSObject 已经有 hash property :

protocol NSObjectProtocol {
var hash: Int { get }

而且,Swift 1.2 会检测到这些错误的覆盖。来自发行说明:

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:’
}

关于ios - 符合 Swift NSObject 子类的 Objective-C 协议(protocol)的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28718577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com