# variables in swift

In notebook 02, Chris defines this helper function:

// This function prints out the calling function's name.  This 
// is useful to see what is going on in your program.
func trace(function: String = #function) {

that takes this #function argument. From the use of trace I gather its value is the name of the function in which we are when calling trace(). I tried to find more about it and if there are others # arguments like this that we can use in swift but didn’t find anything useful. If someone knows more, I’d love to some more information about those!

Don’t know if this is an exhaustive list, but these can be found under the “Literal Expressions” section in the Swift Programming Language guide:

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.
#dsohandle UnsafeRawPointer The DSO (dynamic shared object) handle in use where it appears.

For example, this was a helper function I used for a while in projects:

public func printCallstack(file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
    #if DEBUG
        print("<< Call stack at \((String(describing:file) as NSString).lastPathComponent): \(function): \(line) >>")
    for symbol in Thread.callStackSymbols {
        print("- \(symbol)")
1 Like

Thanks a lot!

Yep, I think that is a complete list. These work the same way as the old C __FILE__ and __LINE__ macros. When used in a default argument position, they get somewhat magic behavior of being evaluated in the caller’s context, so you get its location. This is important for things like assert etc, which want to report file/line/col location information where a crash happens.

It is also very handy for things like trace :slight_smile:


1 Like