Group Group Group Group Group Group Group Group Group

URLSession Tutorial: Getting Started | raywenderlich.com

In this URLSession tutorial, you’ll learn how to create HTTP requests as well as implement background downloads that can be both paused and resumed.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3244963-urlsession-tutorial-getting-started

Hello @Audrey, @kentoh, can you explain the use of [weak var] in the code snippet below? Why is weak self needed at all? If it is definitely needed to not get into a strong reference cycle, would unowned not be better?

Thanks in advance!
Chris

// 4
if let index = download?.track.index {
  DispatchQueue.main.async { [weak self] in
    self?.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], 
                               with: .none)
  }
}

Hi Christopher, it’s in our Swift style guide: https://github.com/raywenderlich/swift-style-guide#extending-lifetime

But there should also be this guard statement to avoid optional chaining:

 guard let self = self else {
    return
  }

Hi @audrey, thanks for the quick reply and link. I still don’t understand where the need of [weak self] arises as I cannot see where the strong reference in this closure is located. The closure itself is not referenced as a property of the class itself, which I understood from Apple’s Swift programming guide to be the reason for strong references in closures.

I found this explanation: it seems it’s more a case of not reloading the row if the view controller has been released.

actually, Felipe / @airjordan12345 added that weak self so he’ll be able to explain it better :wink:

I believe @Audrey is correct. If we have already release this controller then we don’t do anything due to the optional chaining. To do things without the optional we’d do he if-let unwrap as mentioned before.

While I see why some people prefer unowned as it removes optionality, I always go for weak because there is always a chance that self has been released by the time you get to your closure. If that’s the case, unowned will cause a crasher as it’s not optional, where as with weak you may simply not get past the guard statement or the optional chaining.

You’re certainly free to use unowned if you are fully aware and comfortable with your object’s lifecycles :slight_smile:

1 Like