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("/").
    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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s