Skip to content
This repository was archived by the owner on Aug 8, 2023. It is now read-only.

Commit 2023733

Browse files
author
Kerr Marin Miller
committed
Update section on extending object lifetime
1 parent 6dc14c1 commit 2023733

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

swift/README.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -828,7 +828,19 @@ Variables that are delegates should be `weak`.
828828

829829
### Extending object lifetime
830830

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+
func doSomething() {
835+
self.test.asyncTask() { [weak self] bar in
836+
guard let strongSelf = self else { 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.
832844

833845
**Preferred**
834846
```swift

0 commit comments

Comments
 (0)