Hands-On Design Patterns with Swift
上QQ阅读APP看书,第一时间看更新

Weak references

With weak references, you can safely store a reference to another object without increasing its retain count. This prevents creating cycles with all of the required safety. The weak references are always wrapped into Optionals and, unlike unowned references, when a weak reference gets deallocated, you can safely access it through the Optional interface and check that the object is still set and present at runtime:

class Task {
let description: String
weak var worker: Worker?
init(description: String) {
self.description = description
}
}

class Worker {
var name: String
var currentTask: Task?
init(name: String) {
self.name = name
}
}

let worker = Worker(name: "John Snow")
let task = Task(description: "Night's Watch Commander")
worker.currentTask = task
task.worker = worker

// John snow is the night watch's commander

worker.currentTask = nil

// the task will be deallocated