Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialQasa Lee
18,916 PointsWhat about declaring "self" as "unowned self" rather than "weak self" in the closure?(in SearchResultsController.swift)
extension SearchResultsController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
client.searchForArtist(withTerm: searchController.searchBar.text!) { [weak self] (artists, error) in
self?.dataSource.update(with: artists)
self?.tableView.reloadData()
}
}
}
I suppose that "self"(which is "SearchResultsController") doesn't have a shorter lifetime than its property "client', does that make sense to make it "unowned self" in this closure?
1 Answer
Everton Carneiro
15,994 PointsI've just found a great article on this subject in this link.
As I understand, setting self to unowned is unsafe because you can crash the app if self is no longer in memory. It is like when you force unwrap a value and you find nil on runtime.
Qasa Lee
18,916 PointsQasa Lee
18,916 Points"Only capture variables as unowned when you can be sure they will be in memory whenever the closure is run, not just because you donβt want to work with an optional self." as it says! Thanks!