Logo

dev-resources.site

for different kinds of informations.

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

Published at
12/4/2024
Categories
swift
iosdev
ios
Author
Annurdien Rasyid
Categories
3 categories in total
swift
open
iosdev
open
ios
open
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!

Featured ones: