Complete the code to declare a weak reference to avoid a strong reference cycle.
class Person { var name: String weak var friend: Person? // [1] init(name: String) { self.name = name } }
Using weak before the property declares a weak reference, which helps break strong reference cycles.
Complete the code to declare an unowned reference to avoid a strong reference cycle when the referenced object is expected to always exist.
class Customer { var name: String [1] var card: CreditCard? init(name: String) { self.name = name } }
Use unowned when the reference is expected to always have a value and you want to avoid a strong reference cycle.
Fix the error in the closure capture list to avoid a strong reference cycle.
class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { [[1] self] in if let text = self.text { return "<\(self.name)>\(text)</\(self.name)>" } else { return "<\(self.name) />" } } init(name: String, text: String? = nil) { self.name = name self.text = text } }
Using [unowned self] in the closure capture list avoids a strong reference cycle while assuming self will not be nil.
Fill both blanks to create a dictionary comprehension that stores weak references to Person objects.
var people: [String: [1] Person] = [:] func addPerson(name: String, person: Person) { people[name] = [2] person }
Using a wrapper type like WeakReference allows storing weak references in collections like dictionaries.
Fill all three blanks to complete the WeakReference wrapper class that holds a weak reference to an object.
class WeakReference<T: AnyObject> { [1] var value: T? init(value: T) { self.[2] = value } deinit { print("WeakReference deinitialized") } } let person = Person(name: "Alice") let weakRef = WeakReference(value: [3])
The property value is declared weak to avoid strong reference cycles. The initializer assigns the passed person to value.