Câu hỏi phỏng vấn Swift
Câu hỏi

When is it safe to use...

Câu trả lời

In Swift, it is safe to use an unowned reference when you are certain that the referenced object will always exist for the entire lifetime of the object holding the reference. This means that the referenced object will not be deallocated before the object holding the unowned reference is deallocated. Here are some specific scenarios where using an unowned reference is appropriate:

  1. Same-Lifetime Relationship: When two objects have a relationship where one object does not have a strong hold over the other, but you are confident that the referenced object will always exist as long as the referencing object exists. For example, a Person object and a CreditCard object, where the CreditCard has an unowned reference to the Person because a credit card should always have a holder, and the holder (person) is expected to exist as long as the credit card does[3][7].

  2. Non-Optional Requirement: When you need a non-optional reference to another object, and you are sure that the referenced object will not be nil during the lifetime of the referencing object. Unlike weak references, unowned references are not optional and do not automatically become nil when the referenced object is deallocated[2][9].

  3. Avoiding Retain Cycles in Closures: When using closures, if you are sure that the closure and the instance it captures will always refer to each other and will be deallocated at the same time, you can use [unowned self] to avoid retain cycles. This is particularly useful in scenarios where the closure is guaranteed to be deallocated before or at the same time as the instance[4][11].

Example Scenario

Consider a Person and CreditCard relationship:

class Person {
    var card: CreditCard?
}

class CreditCard {
    unowned let holder: Person
    init(holder: Person) {
        self.holder = holder
    }
}

let john = Person()
let card = CreditCard(holder: john)
john.card = card

In this example, the CreditCard has an unowned reference...

senior

senior

Gợi ý câu hỏi phỏng vấn

junior

What is a Serial Queue?

middle

Explain the difference between DispatchQueue.main.async and DispatchQueue.main.sync ?

middle

What’s a strong reference, and why do we need it?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào