Skip to main content
 首页 » 编程设计

objective-c之使用 getter 的 Objective-C 协议(protocol)上的 Swift 1.2 错误

2024年01月01日52pengyingh

这个 Objective-C 协议(protocol)曾经在 Swift 1.1 中工作,但现在在 Swift 1.2 中出错。

Objective-C 协议(protocol)简化为一个有问题的属性:

@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 
        ^ 

如果我将协议(protocol)(我真的不能这样做,因为它来自第三方)更改为以下内容,代码可以正常编译。

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