2

在 Swift 4.1 中,协议中的弱属性已被弃用,因为编译器无法强制执行它。定义属性的内存行为是符合协议的类的责任。

@objc protocol MyProtocol {
  // weak var myProperty: OtherProtocol /* Illegal in Swift 4.1 */
  var myProperty: OtherProtocol? { get set }
} 
@objc protocol OtherProtocol: class {}

但是,这会MyProject-Swift.h作为一个强大的属性导出:

@protocol MyProtocol
@property (nonatomic, strong) id <OtherProtocol> _Nullable myProperty;
@end

现在,当符合类是用 Objective-C 编写时,我遇到了一个问题:

@interface MyClass: NSObject<MyProtocol>
@property (nonatomic, weak) id <OtherProtocol> myProperty;
@end

错误状态retain (or strong)' attribute on property 'myProperty' does not match the property inherited

我该如何解决这个问题?

4

2 回答 2

3

您的问题确实是生成-Swift.h文件中的强引用。我发现您仍然可以通过@objc weak在属性之前添加来将属性标记为弱,因此它可以在 Swift 标头中正确生成,并且不会触发 Swift 4.1 弃用警告。

@objc protocol MyProtocol {
  // weak var myProperty: OtherProtocol /* Illegal in Swift 4.1 */
  @objc weak var myProperty: OtherProtocol? { get set }
} 
于 2018-04-10T07:55:28.187 回答
1

根据@Hamish 的评论,在 Swift 4.2 解决该问题之前,一个可行的解决方法是使用 clang 的诊断编译指示指令,它不会强制在 Objective-C 中重写协议并且影响有限。

@interface MyClass: NSObject<MyProtocol>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch"
@property (nonatomic, weak) id <OtherProtocol> myProperty;
#pragma clang diagnostic pop
@end
于 2018-04-04T10:06:24.170 回答