Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift assert anyway to print variables in string

Tags:

assert

swift

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?

like image 709
Tobias Avatar asked Jun 25 '14 17:06

Tobias


People also ask

How do you print a variable in Swift?

In Swift, you can print a variable or a constant to the screen using the print() function.

What does the assert () function do Swift?

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.

What does colon mean in Swift?

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.

What is variable in Swift?

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.


2 Answers

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.")
like image 190
macshome Avatar answered Nov 26 '22 09:11

macshome


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
}
like image 23
Alexander Hramov Avatar answered Nov 26 '22 08:11

Alexander Hramov