Complete the code to create a strong reference to an instance.
class Person { var name: String init(name: String) { self.name = name } } var person1: Person? = Person(name: "Alice") var person2 = [1]
Assigning person1 to person2 creates a strong reference to the same instance.
Complete the code to declare a weak reference to avoid a strong reference cycle.
class Person { var name: String weak var friend: Person? // Avoid strong reference cycle init(name: String) { self.name = name } } var alice: Person? = Person(name: "Alice") var bob: Person? = Person(name: "Bob") alice?.friend = [1]
Assigning bob to alice?.friend as a weak reference prevents a strong reference cycle.
Fix the error in the code to prevent a strong reference cycle using unowned reference.
class Customer { let name: String var card: CreditCard? init(name: String) { self.name = name } } class CreditCard { let number: UInt64 unowned let customer: [1] init(number: UInt64, customer: Customer) { self.number = number self.customer = customer } } var john: Customer? = Customer(name: "John Appleseed") john?.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)
The unowned reference must be of the class type Customer to avoid a strong reference cycle.
Fill both blanks to create a dictionary comprehension that stores word lengths only for words longer than 3 characters.
let words = ["apple", "bat", "car", "dolphin"] let lengths = words.reduce(into: [:]) { dict, word in if word.count [1] 3 { dict[word] = [2] } }
The condition word.count > 3 filters words longer than 3 characters, and word.count stores their lengths.
Fill all three blanks to create a dictionary of uppercase keys and values for words longer than 4 characters.
let words = ["swift", "code", "apple", "bug"] let result = words.reduce(into: [:]) { dict, word in if word.count [1] 4 { dict[[2]] = [3] } }
The condition word.count > 4 filters words longer than 4 characters. The dictionary keys are uppercase words, and values are the original words.