使用 getter 的 Objective-C 协议上的 Swift 1.2 错误 [英] Swift 1.2 error on Objective-C protocol using getter
问题描述
这个 Objective-C 协议曾经在 Swift 1.1 中工作,但现在在 Swift 1.2 中出现错误.
This Objective-C protocol used to work in Swift 1.1, but now errors in Swift 1.2.
Objective-C 协议被简化为一个有问题的属性:
Objective-C Protocol stripped down to the one problematic property:
@protocol ISomePlugin <NSObject>
@property (readonly, getter=getObjects) NSArray * objects;
@end
class SomePlugin: NSObject, ISomePlugin {
var objects: [AnyObject]! = nil
func getObjects() -> [AnyObject]! {
objects = ["Hello", "World"];
return objects;
}
}
这是 Swift 1.2 错误:
Here is the Swift 1.2 error:
Plugin.swift:4:1: error: type 'SomePlugin' does not conform to protocol 'ISomePlugin'
class SomePlugin: NSObject, ISomePlugin {
^
__ObjC.ISomePlugin:2:13: note: protocol requires property 'objects' with type '[AnyObject]!'
@objc var objects: [AnyObject]! { get }
^
Plugin.swift:6:9: note: Objective-C method 'objects' provided by getter for 'objects' does not match the requirement's selector ('getObjects')
var objects: [AnyObject]! = nil
^
如果我将协议(我无法真正做到,因为它来自第三方)更改为以下内容,代码编译正常.
If I change the Protocol (which I cannot really do since it is from a third party) to the following, the code compiles fine.
// Plugin workaround
@protocol ISomePlugin <NSObject>
@property (readonly) NSArray * objects;
- (NSArray *) getObjects;
@end
提前致谢.
推荐答案
你可以实现
@property (readonly, getter=getObjects) NSArray * objects;
作为具有 @objc
属性的只读计算属性指定 Objective-C 名称.如果您需要一个存储属性作为后备存储那么你必须单独定义它.示例:
as a read-only computed property with an @objc
attribute
specifying the Objective-C name.
If you need a stored property as backing store
then you'll have to define that separately.
Example:
class SomePlugin: NSObject, ISomePlugin {
private var _objects: [AnyObject]! = nil
var objects: [AnyObject]! {
@objc(getObjects) get {
_objects = ["Hello", "World"];
return _objects;
}
}
}
这篇关于使用 getter 的 Objective-C 协议上的 Swift 1.2 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!