Weak self
There are certain times when you can’t capture self as an unowned reference because it may become nil at some point while running an asynchronous task. For example, an editor edits a certain tutorial and submits her editing feedback on the tutorial’s card as follows:
extension Editor {
var feedback: String {
let tutorialStatus: String
if arc4random_uniform(10) % 2 == 0 { tutorialStatus = "published"
} else {
tutorialStatus = "rejected"
}
return "Tutorial (tutorialStatus) by (self.name)"
}
}
This editor isn’t doing a very good job, and decides to publish or reject a tutorial at random.
Add the editTutorial() method to the Editor extension:
func editTutorial() { queue.async() {
[unowned self] in
let feedback = self.feedback DispatchQueue.main.async {
print(feedback)
}
}
}
This method uses the same GCD code the method you’ve used before. The editing happens on a background thread and the resulting feedback prints on the main thread.
Although there is no reference cycle happening in this case, because you decided you did not want feedback to extend the lifetime of a Editor object, you declared self as unowned. This code isn’t safe however! If for some reason the editor went out of scope before editTutorial had completed, self.feedback would crash when it eventually executed.