Search code examples
swiftweak-referencesswift-protocolsswift4.1

A weak property in Objective-C class implementing a Swift protocol


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?


Solution

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