You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Aug 8, 2023. It is now read-only.
Copy file name to clipboardExpand all lines: swift/README.md
+13-1Lines changed: 13 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -828,7 +828,19 @@ Variables that are delegates should be `weak`.
828
828
829
829
### Extending object lifetime
830
830
831
-
Extend object lifetime using the `[weak self]` and `guard let strongSelf = self else { return }` idiom. `[weak self]` is preferred to `[unowned self]` where it is not immediately obvious that `self` outlives the closure. Explicitly extending lifetime is preferred to optional unwrapping.
831
+
Use `[weak self]` to avoid retain cycles. Within a closure, extend object lifetime using the `[weak self]` and `guard let strongSelf = self else { return }` idiom. For example:
832
+
833
+
```swift
834
+
funcdoSomething() {
835
+
self.test.asyncTask() { [weakself] bar in
836
+
guardlet strongSelf =selfelse { return } // gives self local scope, self will be retained for as long as 'strongSelf' is in scope
837
+
let x = bar.doThis()
838
+
strongSelf.foo= x // safe
839
+
}
840
+
}
841
+
```
842
+
843
+
`[weak self]` is preferred to `[unowned self]` where it is not immediately obvious that `self` outlives the closure. Explicitly extending lifetime is preferred to optional unwrapping.
0 commit comments