Search code examples
swiftclosuresblockweak

how to make a weak pointer to self in swift outside of a block


i want to make a weak pointer to self in swift like how we used to in objective-c like

 __weak Something *weakself = self;

I have found people explaining how to use a 'weak self' inside a block,

    { in [unowned self] ...}

but i dont want to define 'weakself' inside my block, i want to define weakself outside of blocks


Solution

  • Just define a weak reference with the weak keyword:

    weak var weakSelf = self
    

    From the documentation:

    You indicate a weak reference by placing the weak keyword before a property or variable declaration.
    ...
    NOTE: Weak references must be declared as variables, to indicate that their value can change at runtime. A weak reference cannot be declared as a constant.