0
0
Swiftprogramming~10 mins

Strong reference cycles between classes in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a class named Person.

Swift
class [1] {
    var name: String
    init(name: String) {
        self.name = name
    }
}
Drag options to blanks, or click blank then click option'
AHuman
BPerson
CAnimal
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different class name like Human or Animal.
2fill in blank
medium

Complete the code to declare a strong reference property 'apartment' in Person class.

Swift
class Person {
    var name: String
    var [1]: Apartment?
    init(name: String) {
        self.name = name
    }
}
Drag options to blanks, or click blank then click option'
Aroom
Bbuilding
Capartment
Dhouse
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different property name like house or room.
3fill in blank
hard

Fix the error in the Apartment class to avoid a strong reference cycle by making the tenant reference weak.

Swift
class Apartment {
    let unit: String
    [1] var tenant: Person?
    init(unit: String) {
        self.unit = unit
    }
}
Drag options to blanks, or click blank then click option'
Astrong
Blazy
Cunowned
Dweak
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'strong' or 'unowned' which do not break the cycle.
Using 'lazy' which is unrelated here.
4fill in blank
hard

Fill both blanks to complete the code that creates a strong reference cycle between Person and Apartment.

Swift
let john = Person(name: "John")
let unit4A = Apartment(unit: "4A")
john.[1] = unit4A
unit4A.[2] = john
Drag options to blanks, or click blank then click option'
Aapartment
Btenant
Cowner
Dresident
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect property names like owner or resident.
5fill in blank
hard

Fill all three blanks to complete the code that breaks the strong reference cycle using weak reference and optional chaining.

Swift
class Apartment {
    let unit: String
    [1] var tenant: Person?
    init(unit: String) {
        self.unit = unit
    }
}

let john = Person(name: "John")
let unit4A = Apartment(unit: "4A")
john.[2] = unit4A
unit4A.tenant = john
unit4A.tenant?.[3] = nil
Drag options to blanks, or click blank then click option'
Aweak
Bapartment
Cname
Dstrong
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'strong' instead of 'weak' for tenant.
Using wrong property names for john's apartment or tenant's property.