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

Swift

Swift Problem Overview


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?

Swift Solutions


Solution 1 - Swift

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")

Solution 2 - Swift

The Swift Language Reference defines a few "special literals" that offer this behavior:

Literal        Type     Value

#file          String   The name of 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.

Solution 3 - Swift

You can get just the file name this way

Swift 5

let errorLocation =  (#file as NSString).lastPathComponent
print(errorLocation)

or get with separator from last component

let errorLocation = filePath.components(separatedBy: "/").last!
print(errorLocation)

Output

ViewController.swift

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionphoganuciView Question on Stackoverflow
Solution 1 - SwifthfossliView Answer on Stackoverflow
Solution 2 - SwiftnathanView Answer on Stackoverflow
Solution 3 - SwiftYunus T.View Answer on Stackoverflow