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?
Asked
Active
Viewed 2.0k times
3 Answers
144
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")
hfossli
- 22,108
- 10
- 113
- 129
-
3Swift 2.2 changes are now released and should be the new approved answer :) – Bersaelor Mar 22 '16 at 13:19
-
1`#` is happening in 2.2. – Zigii Wong Mar 23 '16 at 07:04
-
#namespace is not a identifier. – c0ming Apr 25 '16 at 01:47
-
Why have all of those parameters? you wouldn't want to actually change them right? – Joey Nelson Aug 19 '20 at 01:31
-
Yep, you would only use them to capture call site information like file and line number. So normal usage would be `track("enters app")` without specifying the others. – hfossli Sep 17 '20 at 18:47
97
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.
Fogmeister
- 73,141
- 39
- 203
- 288
nathan
- 5,376
- 2
- 25
- 24
8
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
Yunus T.
- 431
- 7
- 9