0
0
Swiftprogramming~10 mins

Unowned references for guaranteed lifetime 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 an unowned reference to avoid retain cycles.

Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Apartment {
    unowned var tenant: [1]
    init(tenant: Person) {
        self.tenant = tenant
    }
}
Drag options to blanks, or click blank then click option'
AString
BApartment
CInt
DPerson
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value type like String or Int for unowned reference.
Using the wrong class name for the unowned property.
2fill in blank
medium

Complete the code to declare an unowned reference correctly.

Swift
class Customer {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class CreditCard {
    unowned [1] customer: Customer
    init(customer: Customer) {
        self.customer = customer
    }
}
Drag options to blanks, or click blank then click option'
Avar
Bunowned
Clet
Dweak
Attempts:
3 left
💡 Hint
Common Mistakes
Using var instead of let for unowned reference.
Confusing weak and unowned references.
3fill in blank
hard

Fix the error in the code by choosing the correct keyword for the reference to avoid a runtime crash.

Swift
class Owner {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class House {
    [1] var owner: Owner?
    init(owner: Owner) {
        self.owner = owner
    }
}
Drag options to blanks, or click blank then click option'
Aweak
Blazy
Cunowned
Dstrong
Attempts:
3 left
💡 Hint
Common Mistakes
Using unowned for optional references that can become nil.
Using strong reference causing retain cycles.
4fill in blank
hard

Fill both blanks to create a class with an unowned reference and initialize it properly.

Swift
class Driver {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Car {
    [1] var driver: Driver
    init(driver: [2]) {
        self.driver = driver
    }
}
Drag options to blanks, or click blank then click option'
Aunowned
Bweak
CDriver
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using weak instead of unowned for guaranteed lifetime.
Using wrong type for the parameter.
5fill in blank
hard

Fill all three blanks to create a pair of classes with unowned references to avoid retain cycles.

Swift
class Teacher {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Classroom {
    [1] var teacher: Teacher
    init(teacher: [2]) {
        self.teacher = teacher
    }
    func assignTeacher() -> [3] {
        return teacher.name
    }
}
Drag options to blanks, or click blank then click option'
Aunowned
BTeacher
CString
Dweak
Attempts:
3 left
💡 Hint
Common Mistakes
Using weak instead of unowned for guaranteed lifetime.
Returning wrong type from the function.