2014-11-20

My Swift equivalent of C macro DLog() with __PRETTY_FUNCTION__.

I did not see this exact thing out in the wild yet. It is cobbled together from unpopular Stack Overflow answers and highly informative blog posts.

func dLog(message: String, fullPath: String = __FILE__, line: Int = __LINE__, functionName: String = __FUNCTION__) {
    let filename = fullPath.lastPathComponent
    // Remove ".swift" from file name.
    let splitFilename = split(filename, {(c:Character)->Bool in return c=="."}, allowEmptySlices: false)
    let classGuess = splitFilename[0]
    // Remove "()" from function name.
    let splitFuncName = split(functionName, {(c:Character)->Bool in return c=="("}, allowEmptySlices: false)
    let funcName = splitFuncName[0]
    NSLog("%@", "[\(classGuess) \(funcName)] [Line \(line)] \(message)")
}

The output looks like this.

2014-11-19 18:55:05.887 SandboxApp[12433:287724] [SomeViewController viewDidLoad] [Line 27] dLog message test.

Note that the biggest flaw is the use of the file name instead of the class name. According to Swift docs there is no __CLASS__ special literal expression.

To make this global, I dropped it in the AppDelegate file outside of the AppDelegate class. There has got to be a better convention for global functions, but I am only burning one bridge at a time.

For bonus points, the Xcode autocomplete on the split() function crashed SourceKitService. I guess this means I'm cutting edge now.


No comments:

Post a Comment