Hey. I am trying to figure out what assertion exactly does. As above, assertion did not cause printing out the message that I put. So what is the point of passing that message? Are these purely made to catch on mistakes on an early stage? Many thanks.
I wonder whether you meant to use:
assert(num > 300, "\(num) < 300")
The output would then start with:
Assertion failed: Optional(234) < 300
That particular assertion isn't very great. The message is approximately useless (it doesn't tell you anything you couldn't glean from the source code), and it's just a toy example.
age is example is understandable, but unlikely in the real world. If that age comes from user input, you should handle erroneous cases gracefully. Users make mistakes and typos, and that shouldn't crash your app.
Assertions exist to establish preconditions in your code, or crash and die. Consider the case when your main view controller has a
@IBOutlet. You may want to assert that it's non-nil. That's not a recoverable error: you forgot to hook up the outlet in Interface Builder before building your app, and there's nothing your app could reasonably do at runtime to recover from that. Doing this might be reasonable:
assert(mainView != nil, "The mainView IBOutlet wasn't connected") assert(mainView is MainView, "The mainView was expected to have type MainView, but was actually of type \(type(of: mainView)")
The output from a failed assertion consists of
Assertion failed: , then your custom message, then the location.
In a playground,
let age = -3 assert(age >= 0, "CUSTOM MESSAGE")
this results in the following output:
Assertion failed: CUSTOM MESSAGE: file Playground.playground, line 2
The message argument can use all the features of string literals, including string interpolation. For example:
let age = -3 assert(age >= 0, "Age (\(age)) cannot be less than 0")
Assertion failed: Age (-3) cannot be less than 0: file Playground.playground, line 2
Shouldn’t the assertion for this output be:
let age = -3 let threshold = 0 assert(age >= threshold, "Age (\(age)) cannot be less than \(threshold)")
I didn’t paste a change back in; oops. You’re right.