Skip to content

[swift2objc] Add support for Swift ARC Features (weak and unowned variables) and lazy variables #2053

Open
@nikeokoronkwo

Description

@nikeokoronkwo

From https://docs.swift.org/swift-book/documentation/the-swift-programming-language/automaticreferencecounting:

A weak reference is a reference that doesn’t keep a strong hold on the instance it refers to, and so doesn’t stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing the weak keyword before a property or variable declaration.

Like a weak reference, an unowned reference doesn’t keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. You indicate an unowned reference by placing the unowned keyword before a property or variable declaration.

Annotating with @objc should suffice for both

In Objective-C, weak properties are represented as weak in the @property declarations in Objective-C (as well as _Nullable since weak properties are nullable), while unowned properties are represented as unsafe_unretained.

public class RefClass {
  // declarations...
}

public class MyClass {
  weak var myWeakVar: RefClass?
  unowned var myUnownedVar: RefClass

  init(_ myVar: RefClass) { self.myUnownedVar = myVar }

  // ...
}

assuming wrapped and annotated with @objc, exporting should produce

@interface RefClass: NSObject
// exported decls...
@end

@interface MyClass: NSObject
@property (nonatomic, unsafe_unretained) RefClass * _Nonnull myUnownedVar;
@property (nonatomic, weak) RefClass * _Nullable myWeakVar;
// other decls...
@end

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions