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

Explain the difference between weak and...

Câu trả lời

In Swift, both weak and unowned references are used to avoid strong reference cycles, which can lead to memory leaks. However, they have distinct characteristics and use cases.

Weak References

A weak reference is a reference that does not prevent the referenced object from being deallocated. When the object is deallocated, the weak reference is automatically set to nil. This means that weak references must always be optional types.

Characteristics:

  • Optional: Weak references are always declared as optional because they can be set to nil when the referenced object is deallocated.
  • Automatic Nil Assignment: When the referenced object is deallocated, the weak reference is automatically set to nil.
  • Use Case: Use weak references when the referenced object can be deallocated at any time, such as in parent-child relationships where the child should not keep the parent alive.

Example:

class Parent {
    var child: Child?
}

class Child {
    weak var parent: Parent?
}

var parent: Parent? = Parent()
var child: Child? = Child()

parent?.child = child
child?.parent = parent

parent = nil
// At this point, the child’s parent reference is automatically set to nil

Unowned References

An unowned reference is a non-optional reference that does not keep a strong hold on the referenced object. Unlike weak references, unowned references are not set to nil when the referenced object is deallocated. Instead, accessing an unowned reference after the object has been deallocated will cause a runtime crash.

Characteristics:

  • Non-Optional: Unowned references are non-optional and are assumed to always have a value.
  • No Automatic Nil Assignment: Unowned references are not set to nil when the referenced object is deallocated. Accessing a deallocated unowned reference will cause a runtime error.
  • Use Case: Use unowned references when you are certain that the referenced object will not be deallocated before the reference is accessed, such as in parent-child relationships where the parent should not keep the child alive.

Example:

class Customer {
    var card: CreditCard?
}

class CreditCard {
    unowned let customer: Customer
    
    init(customer: Customer) {
        self.customer = customer
    }
}

var customer: Customer? = Customer()
customer?.card = CreditCard(customer: customer!)

// At this point, the customer and card reference each other
customer = ni...
senior

senior

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

expert

What is the difference between @escaping and @nonescaping Closures in Swift?

middle

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

middle

When to use @objc attribute?

Bình luận

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

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