Swift: Hunting down the fleeting debugPrint differentiation

Yes, I had to build a little test bed to find items that printed differently in debugPrint than they did in print. I thought I’d share. Surely this kind of bizarre little implementation of a command-line test will be of interest to someone out there.

You might ask: why not playgrounds. The answer is that printing to any output stream type (including strings) crashes playgrounds. A playground version would use XCPlayground to continue execution instead of a run loop.

import Cocoa

// Items to check
//let x = "Snoop"
//let x = 1...5
let x = UnicodeScalar(0x1f601)

// Build test cases
var a = ""; print(x, &a, appendNewline:false); print(a)
var b = ""; debugPrint(x, &b, appendNewline:false); print(b)

// Compare and alert
func ExitAfter(t: Double, _ status: Int32) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 
        numericCast(UInt64(t * Double(NSEC_PER_SEC)))), 
        dispatch_get_global_queue(
            DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
        {exit(status)})
}

if a != b {
    // Success
    print("YES!")
    NSSound(named: "Sosumi")?.play()
    ExitAfter(0.5, 0)
    CFRunLoopRun() // stick around to produce sound
} else {print("No")}

Comments are closed.