Background: In Objective-C, I would create my assertion with debug information included:
NSAssert(poetCount > 5, "Expected poetCount > 5; Actual: %d", poetCount);
However, the global assert
function in Swift doesn't seem to allow this, because the message parameter is a StaticString. So I can NOT do this:
assert(NSFileManager.defaultManager().fileExistsAtPath(fullpath),
"Expected: File to Exist @ \(fullpath)")
Question: Is there an alternative assert
function that does not require a static string, or should I continue using NSAssert
if I want to put in extra information to make debugging easier?
In Swift, you can print a variable or a constant to the screen using the print() function.
Swift lets you force an app crash using the assert() function. This takes two parameters: a condition to check, and a message to print if the assertion fails.
The colon in the declaration means “…of type…,” so the code above can be read as: “Declare a variable called welcomeMessage that's of type String .” The phrase “of type String ” means “can store any String value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored.
1. Swift Variables. In programming, a variable is a container (storage area) to hold data. For example, var num = 10. Here, num is a variable storing the value 10.
I don't think you can currently because of the StaticString param. I tried setting the message string with a let but you can't even put a variable in there it seems. It has to be a StaticString in quotes.
For what it's worth, Apple's sample code follows the same pattern:
assert(listItems && listItems!.count == 1, "There must be exactly one moved item.")
You can write your own version of assert with String. Here is example:
func assert(condition: @autoclosure () -> Bool, _ message: String = "") {
#if DEBUG
if !condition() {
println(message);
abort()
}
#endif
}
or with additional debug info:
func assert(condition: @autoclosure () -> Bool, _ message: String = "", file: String = __FILE__, line: Int = __LINE__) {
#if DEBUG
if !condition() {
println("assertion failed at \(file):\(line): \(message)");
abort()
}
#endif
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With