这个Objective-C协议曾经在Swift 1.1中工作,但现在Swift 1.2中存在错误。
Objective-C协议剥离了一个有问题的属性:
@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错误:
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
^
如果我将协议(我不能真正做到,因为它来自第三方)更改为以下内容,则代码编译正常。
// Plugin workaround
@protocol ISomePlugin <NSObject>
@property (readonly) NSArray * objects;
- (NSArray *) getObjects;
@end
提前致谢。
答案 0 :(得分:3)
您可以实施
@property (readonly, getter=getObjects) NSArray * objects;
作为具有@objc
属性的只读计算属性
指定Objective-C名称。
如果需要存储属性作为后备存储
那么你必须单独定义它。
例如:
class SomePlugin: NSObject, ISomePlugin {
private var _objects: [AnyObject]! = nil
var objects: [AnyObject]! {
@objc(getObjects) get {
_objects = ["Hello", "World"];
return _objects;
}
}
}