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

Do we need to use [weak self] or...

Câu trả lời

When asked whether to use [weak self] or [unowned self] in a closure, the decision depends on the specific context and the lifecycle of the objects involved. Here are the key considerations:

When to Use [weak self]

  1. Avoiding Retain Cycles:

    • Use [weak self] when you want to avoid retain cycles, especially in escaping closures that might outlive the object they capture. This is common in asynchronous operations, such as network requests or delayed tasks.
    • Example:
      swift Copy
      DispatchQueue.main.async { [weak self] in
          guard let self = self else { return }
          self.updateUI()
      }
    • In this example, using [weak self] ensures that the closure does not keep a strong reference to self, preventing a retain cycle if self is deallocated before the closure is executed[1][3][5].
  2. Optional Self:

    • [weak self] makes self an optional within the closure. This means you need to safely unwrap self before using it, typically with guard let or optional chaining.
    • Example:
      swift Copy
      self?.doSomething()

When to Use [unowned self]

  1. Guaranteed Lifetime:

    • Use [unowned self] when you are certain that the object will exist for the entire lifetime of the closure. This is typically used when the closure and the object it captures will be deallocated at the same time.
    • Example:
      swift Copy
      someFunction { [unowned self] in
          self.doSomething()
      }
    • In this case, self is not optional, and you can use it directly without unwrapping. However, if self is deallocated before the closure is executed, it will cause a runtime crash[3][9][12].
  2. Performance Considerations:

    • [unowned self] can be slightly more performant than [weak self] because it does not involve optional unwrapping and stores less metadata. However, this comes with the risk of crashes if the object is deallocated prematurely[12].

Practical Example

Consider a scenario where you have a view controller that performs a network request and updates the UI upon completion:

swift Copy
class MyViewController: UIViewController {
    func fetchData() {
        networkRequest { [weak self] data in
            guard let self = self else { return }
            self.updateUI(wit...
expert

expert

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

middle

What is typecasting?

middle

When would you use self in a method?

junior

What’s the difference between == and === ?

Bình luận

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

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