Assertions are ** features that describe the conditions that a program must meet at some point. ** ** If the conditions are not met, the program execution will be interrupted.
The assertion causes a run-time error and terminates the program. ** Run-time errors occur only during debugging. ** **
At the time of release, processing continues regardless of the success or failure of the conditional expression. Isn't it quite convenient for me personally? I think.
Use the standard library assert ()
and assertionFailure ()
functions.
The assert () function ** A function for declaring the conditions that should be met when this function is executed. ** ** If the conditions are not met when this function is executed, a run-time error will occur.
The first argument of the assert () function is a conditional expression, and the second argument is the message at the end.
** If the conditional expression is true, continue the subsequent processing and continue. If false, the message, file name, and line number passed as the second argument are output. ** **
let a = 10
let b = 11
assert(a == b, "The values of a and b are different.")
Execution result
Assertion failed:The values of a and b are different.: file __lldb_expr_383/MyPlayground.playground, line 5
The assertionFailure () function is an assertion that always fails with no ** conditional expression. ** **
Because the execution itself does not meet the conditions ** Similar to the assert () function with false as the first argument. ** **
In the following sample code The season is output based on the value passed to the argument.
A run-time error will occur if there is no corresponding season for the passed value.
func printSeason(month: Int) {
switch month {
case 1...2, 12:
print("winter")
case 3...5:
print("spring")
case 6...8:
print("summer")
case 9...11:
print("autumn")
default:
assertionFailure("Set a value from 1 to 12.")
}
}
printSeason(month: 1)
printSeason(month: 10)
printSeason(month: 100)
Execution result
winter
autumn
Fatal error:Set a value from 1 to 12.: file __lldb_expr_385/MyPlayground.playground, line 13
By declaring the range of values that the function expects using assertions, You can detect unexpected values when debugging.
Unlike the fatalError () function, which terminates the program even at release time At the time of release, the assertion will continue to execute the program even in unexpected situations.
** In other words, it decides whether to continue or interrupt the process when an unexpected situation occurs. ** **
The above is also an explanation of assertions.
Assertions and fatalError () are not common and It's not that difficult, so I think it's enough to put it in the corner of your head!
I also have an article about other error handling, so please have a look.
-[Swift] Perform error handling with Optional \
Thank you for watching until the end.
Recommended Posts