Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To display the name of the method and line number in Swift while printing, you can use the following code:

func printDebug(_ message: String = "", file: String = #file, line: Int = #line, function: String = #function) {
    let fileName = file.split(separator: "/").last ?? ""
    print("[Debug] \(fileName):\(line) \(function) - \(message)")
}

This code defines a printDebug function that takes an optional message parameter, as well as default parameters for file, line, and function. The file and line parameters are used to get the name of the file and the line number where printDebug is called, while the function parameter is used to get the name of the function.

To use this function, simply call it like this:

printDebug("This is a debug message")

This will print a message like this:

[Debug] MyFile.swift:12 myFunction() - This is a debug message

where MyFile.swift is the name of the file where printDebug is called, 12 is the line number, myFunction is the name of the function, and This is a debug message is the message passed to printDebug.