Complete the code to create a strong reference cycle that can cause a memory leak.
class Person { var name: String var apartment: Apartment? init(name: String) { self.name = name } } class Apartment { var unit: String var tenant: Person? init(unit: String) { self.unit = unit } } var john: Person? = Person(name: "John") var unit4A: Apartment? = Apartment(unit: "4A") john?.apartment = unit4A unit4A?.tenant = [1]
Assigning john to unit4A?.tenant creates a strong reference cycle causing a memory leak.
Complete the code to break the strong reference cycle using a weak reference.
class Person { var name: String weak var apartment: [1]? init(name: String) { self.name = name } }
Declaring apartment as a weak reference to Apartment breaks the strong reference cycle.
Fix the error in the closure to avoid a memory leak by capturing self correctly.
class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { [1] 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 prevents a strong reference cycle by not strongly capturing self.
Fill both blanks to create a dictionary comprehension that filters and transforms data without causing memory leaks.
let words = ["apple", "bee", "cat", "dog"] let filteredLengths = words.reduce(into: [:]) { dict, word in if word.count [1] 3 { dict[word.[2]()] = word.count } }
The code filters words with length greater than 3 and uses the lowercase version of the word as the key.
Fill all three blanks to create a dictionary comprehension that maps uppercase keys to values filtered by a condition.
let data = ["a": 1, "b": 2, "c": 3, "d": 4] let result = data.filter { $0.value [1] 2 } .reduce(into: [:]) { dict, pair in dict[[2]] = [3] }
The code filters entries with values greater than 2 and maps keys to uppercase with their values.