Swift 使用 getter Objective-C 协议的 1.2 错误

Swift 1.2 error on Objective-C protocol using getter

此 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

提前致谢。

你可以实施

@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;
        }
    }
}