Ask Your Question
4

What is the process to display the name of the method and line number in Swift while printing?

asked 2021-10-30 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-03-04 01:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-30 11:00:00 +0000

Seen: 10 times

Last updated: Mar 04 '22