DEV Community

Annurdien Rasyid
Annurdien Rasyid

Posted on

Enhance Debugging in Swift with #file, #line, and #function

Swift provides three special literals: #file, #line, and #function. These are automatically set to the current file name, line number, and function name, respectively. They are especially handy when creating custom logging functions or test predicates.

import Foundation

func log(_ message: String, _ file: String = #file, _ line: Int = #line, _ function: String = #function) {
    print("[\(file):\(line)] \(function) - \(message)")
}

func foo() {
    log("Hello world!")
}

foo() // [TryDebug.playground:8] foo() - Hello world!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)