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

user1709076 picture user1709076 · Apr 19, 2015 · Viewed 14.3k times · Source

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

Answer

Martin R picture Martin R · Apr 19, 2015

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.