Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print call stack in Swift?

In Objective-C, you can print the call stack by doing the following:

NSLog(@"%@", [NSThread callStackSymbols]);

How do you do this in Swift without using Foundation class?

like image 832
Boon Avatar asked Jun 10 '15 11:06

Boon


People also ask

How do I print a stack trace in Swift?

In Objective-C, you can print the call stack by doing the following: NSLog(@"%@", [NSThread callStackSymbols]);

What is stack trace stack call?

a call stack is a stack data structure that stores information about the active subroutines of a computer program. A stack trace is a report of the active stack frames at a certain point in time during the execution of a program.


3 Answers

As Jacobson says, use the following:

Swift 2:

print(NSThread.callStackSymbols())

Swift 3 / Swift 4:

print(Thread.callStackSymbols)

That's Swift code. It's using a Foundation method, but so does 90%+ of what you do on iOS.

EDIT:

Note that the formatting looks better if you use:

Thread.callStackSymbols.forEach{print($0)}

From the debugger command line you can type

e Thread.callStackSymbols.forEach{print($0)}
like image 183
Duncan C Avatar answered Oct 18 '22 00:10

Duncan C


For Swift 3 use:

print(Thread.callStackSymbols)

or for better formatting

for symbol: String in Thread.callStackSymbols {
    print(symbol)
}
like image 43
Doug Amos Avatar answered Oct 18 '22 00:10

Doug Amos


This improves the output a little.

for symbol: String in NSThread.callStackSymbols() {
    NSLog("%@", symbol)
}
like image 6
Kevin Snow Avatar answered Oct 18 '22 01:10

Kevin Snow