问题
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