Blended Cocoa

Adventures in Objective-C, Swift and Cocoa

__FILE__, __FUNCTION__, __LINE__ and __COLUMN__ as Defaults in Swift

I was experimenting with methods of debug logging in Swift and came across an interesting find. If you use the __FILE__, __FUNCTION__, __LINE__ and __COLUMN__ “macros” as default function parameter values in Swift the value is set to the file, function etc of the caller rather than the details of the called functions location.

This means you can automatically pass information about a calling function by providing default values. For example:

1
2
3
4
5
6
7
func DLog(message: String, file: String = __FUNCTION__, function: String = __FILE__, line: Int = __LINE__, column: Int = __COLUMN__) {
  println("\(file) : \(function) : \(line) : \(column) - \(message)")
}

func applicationDidFinishLaunching(aNotification: NSNotification?) {
  DLog("App Did Finish Launching")
}

This will display a message of the form:

1
.../AppDelegate.swift : applicationDidFinishLaunching : 16 : 14 - App Did Finish Lauching

Clearly __FILE__, __FUNCTION__, __LINE__ and __COLUMN__ are not implemented using a preprocessor but then we knew that already.

Comments