Swift - Capturing closures - Apple's swift programming guide snippet

76 views Asked by At

In Apple's Swift programming guide, "Automatic Reference Counting" section, at "Resolving Strong Reference Cycles for Closures", This snippet is mentioned:

lazy var someClosure: () -> String = {
    [unowned self, weak delegate = self.delegate!] in
    // closure body goes here
}

What is the point of the exclamation mark in the assignment "weak delegate = self.delegate!"?

I mean, why do you care if there is a value or not? In either ways, you will be receiving an optional delegate inside the closure body since delegate is declared weak, which must be optional, and you will have to access it as an optional.

On the other hand, if you know for sure there 'self.delegate' wont be nil when you access it, why not declaring it as unowned?

Therefore, why is the force unwrapping necessary here? Can someone shed some light on this?

1

There are 1 answers

1
Tristan Burnside On

As there is not really any more context in the text around this example the only person who can know for sure is the author or maintainer of the Swift programming guide.

But here are some possible reasons that I can think of (in no particular order)

  • The author made a mistake (it happens)
  • It was required in an older version of Swift and the documentation has not been updated (keeping documentation up to date is hard)
  • The author wanted to make it obvious to others that creating the block if the delegate does not exist is a bug
  • The author wants to make it easier to track cases when a delegate was deallocated between creating the block and calling it (maybe for analytics purposes?)