Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get line number and function name in Swift language?

Tags:

swift

In Objective-C, we could use the __LINE__ and __PRETTY_FUNCTION__ macros. These are not exposed in the Swift language. Is there another way to get similar information in Swift?

like image 582
phoganuci Avatar asked Jun 08 '14 05:06

phoganuci


People also ask

How do I get line numbers in Swift?

In Swift, you can use #file #function line #column to get the debug info you want.

What is #function in Swift?

Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed.


1 Answers

Literal     Type              Value  #file       String            The path to the file in which it appears. #fileID     String            The name of the file and module in which it appears. #filePath   String            The path to the file in which it appears. #line       Int               The line number on which it appears. #column     Int               The column number in which it begins. #function   String            The name of the declaration in which it appears. #dsohandle  UnsafeRawPointer  The dynamic shared object (DSO) handle in use where it appears. 

See documentation for more information

Example:

print("Function: \(#function), line: \(#line)")  

With default values in parameters you can also create a function:

public func track(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) {      print("\(message) called from \(function) \(file):\(line)")  } 

which can be used like this

track("enters app") 
like image 197
hfossli Avatar answered Sep 18 '22 15:09

hfossli