Logging in Swift

Printing meaningful logs from a Swift program is tricky, mainly because there is no way to get the current function’s “pretty” names, e.g. there is no real alternative to Objective-C’s magic constant __PRETTY_FUNCTION__.

Luckily other magic constants do exist in Swift, like __FILE__ and __FUNCTION__ — see https://developer.apple.com/swift/blog/?id=15. Concatenating __FILE__ and __FUNCTION__ is an okay approximation of the full function signature in most cases. The logs would be overly verbose though as  __FILE__ contains the full path name and extension as well. We can get rid of the noise with some string manipulations:

func Log(message: String = "",
         _ path: String = __FILE__,
         _ function: String = __FUNCTION__) {
    let module = path.componentsSeparatedByString("/").
        last!.componentsSeparatedByString(".").first!
    NSLog("\(module).\(function): \(message)")
}

A finishing touch could be to disable logging in release builds, by wrapping the function body in #if DEBUG/#endif.

Leave a comment