Swift 1.2 error on Objective-C protocol using getter

前提是你 提交于 2020-01-02 23:19:11

问题


This Objective-C protocol used to work in Swift 1.1, but now errors in Swift 1.2.

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

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

Thanks in advance.


回答1:


You can implement

@property (readonly, getter=getObjects) NSArray * objects;

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


来源:https://stackoverflow.com/questions/29594304/swift-1-2-error-on-objective-c-protocol-using-getter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!