2

In Swift 4.1, weak properties have been deprecated in protocols, since the compiler has no way to enforce it. It is the responsibility of the class conforming to the protocol to define the memory behaviour of the property.

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

However, this gets exported to MyProject-Swift.h as a strong property:

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

And now I have an issue when the conforming class is written in Objective-C:

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

The error states retain (or strong)' attribute on property 'myProperty' does not match the property inherited.

How can I solve this?

KPM
  • 10,558
  • 3
  • 45
  • 66
  • 2
    Note that this will be (re)allowed in Swift 4.2 for `@objc` protocols: https://github.com/apple/swift/pull/15274. Until then, you'll have to implement the protocol in Obj-C. – Hamish Apr 04 '18 at 09:47
  • @Hamish Thanks! Unbelievable that no-one saw this issue before it was released. – KPM Apr 04 '18 at 09:54

2 Answers2

3

Your problem is indeed the strong reference in the generated -Swift.h file. I found out that you can still mark the property as weak by adding @objc weak before the property, so it gets generated correctly in the Swift header and not trigger the Swift 4.1 deprecation warning.

@objc protocol MyProtocol {
  // weak var myProperty: OtherProtocol /* Illegal in Swift 4.1 */
  @objc weak var myProperty: OtherProtocol? { get set }
} 
Joris Timmerman
  • 1,482
  • 14
  • 25
1

Based on @Hamish's comment, a livable workaround until Swift 4.2 solves the issue, that doesn't force to rewrite the protocol in Objective-C and has a limited impact, would be to use clang's diagnostics pragma instruction.

@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
KPM
  • 10,558
  • 3
  • 45
  • 66