Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different class name like Human or Animal.
✗ Incorrect
The class is named Person, so the blank should be filled with 'Person'.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different property name like house or room.
✗ Incorrect
The property name is 'apartment' to represent the relationship.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'strong' or 'unowned' which do not break the cycle.
Using 'lazy' which is unrelated here.
✗ Incorrect
The 'tenant' property should be declared weak to avoid a strong reference cycle.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect property names like owner or resident.
✗ Incorrect
The Person's apartment property is set to unit4A, and Apartment's tenant property is set to john, creating a strong reference cycle.
5fill in blank
hardFill 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'
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.
✗ Incorrect
The tenant property is weak, john's apartment is set, and the tenant's apartment is accessed with optional chaining to set it to nil, breaking the cycle.