what assert statement does and what it does in CloudKitShare sample project?

What does the following line do in the code snippet from CloudKitShare Apple sample Xcode project that I show after that?

  assert(zoneID == self.zone.zoneID)
// Update the server change token.
//
operation.recordZoneChangeTokensUpdatedBlock = { (zoneID, serverChangeToken, _) in
  assert(zoneID == self.zone.zoneID)
  self.setServerChangeToken(newToken: serverChangeToken)
}

The documentation for the assert statement says that when the project build is -0none and also in Playground, the code terminates completely, and not just exit from the current code, do I understand that correctly? The documentation seems to assume I understand C-style programming.

You can ignore "C-style" in the description. It's only really helpful to people coming from a C programming background (so they can relate Swift's assert function to the function they're already familiar with in C).

Small details aside, it's really pretty straightforward:

  • Use assert if you want your app to crash if the condition is false, while you're running in debug mode, such as in Xcode. If you're in Xcode, the crash will be caught by the debugger, so your app will stop at the line with the assert, similar to a breakpoint. In release mode, the assert won't do anything at all.

  • Use precondition instead of assert if you want your app to crash if the condition is false, when you're running in debug or release mode. Again, if you're using a debugger, then the debugger will stop at the precondition line.

  • Use fatalError if you want to absolutely guarantee that you app will crash, regardless of compilation mode.

The idea behind assert is that you might want to check for unexpected conditions while debugging, but you don't want to risk your app crashing after release if you forget to remove the assert calls.

Bonus detail #1: Actually, it's possible to create a release build in so-called "unchecked" mode. This will prevent even precondition from crashing your app. However, it's very unlikely that you would ever make an "unchecked" build, so you don't really need to consider this special case.

Bonus detail #2: All three of these functions (assert, precondition and fatalError) have an optional String parameter that you can use to provide a customized message when the function triggers a crash.

what assert statement does and what it does in CloudKitShare sample project?
 
 
Q