-1

I was reading apple swift programming language and I didnt understand what is assert function and when we use it?

assert(condition: Bool, message: String)
vadian
  • 274,689
  • 30
  • 353
  • 361
Mahdi
  • 94
  • 10
  • http://www.apeth.com/swiftBook/ch05.html#_aborting_the_whole_program – matt Mar 04 '17 at 19:31
  • And see example in answer here: http://stackoverflow.com/a/42443881/341994 – matt Mar 04 '17 at 19:32
  • Did you take a look at [the documentation](https://developer.apple.com/reference/swift/1541112-assert) for `assert`? *"Use this function for internal sanity checks that are active during testing but do not impact performance of shipping code.*" – Hamish Mar 04 '17 at 19:53

1 Answers1

0

Assert provides a way for your code to reflect your assumptions explicitly, and check them when your code is running. Ideally, they are never triggered.

In an unlikely situation when an assertion is triggered, the message lets you know that your code has been modified in a way that breaks your assumption. This is very valuable, because it shrinks the area in which you search for newly introduced errors.

This is easier to understand with an example. Suppose that your code gets end-user input, and ensures that your end-user checks off at least one value in a list of check boxes. Another part of the code gets the list, and assumes that it is not empty. This is a good place to use an assertion: you assert that the list has non-zero size, and add a message explaining that your input form has validated the list before.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523