How to print call stack in Swift?

后端 未结 5 1631
野性不改
野性不改 2020-12-23 11:19

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

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

How do you do this in Swi

相关标签:
5条回答
  • 2020-12-23 11:46

    This improves the output a little.

    for symbol: String in NSThread.callStackSymbols() {
        NSLog("%@", symbol)
    }
    
    0 讨论(0)
  • 2020-12-23 11:53

    Here's a great utility class I found on github:

    https://github.com/nurun/swiftcallstacktrace

    You get a tuple (class,method) of any stack trace symbol so you can do a clean printout.

    CallStackAnalyser.classAndMethodForStackSymbol(NSThread.callStackSymbols()[2])
    

    Edit: swift 4.1 update

    https://github.com/GDXRepo/CallStackParser

    0 讨论(0)
  • 2020-12-23 12:08

    For Swift 3 use:

    print(Thread.callStackSymbols)
    

    or for better formatting

    for symbol: String in Thread.callStackSymbols {
        print(symbol)
    }
    
    0 讨论(0)
  • 2020-12-23 12:08

    I needed to write the callstack to a log file so I tweaked it like so.

    var ErrorStack = String()
    Thread.callStackSymbols.forEach {
        print($0)
        ErrorStack = "\(ErrorStack)\n" + $0
    }
    
    0 讨论(0)
  • 2020-12-23 12:10

    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)}
    
    0 讨论(0)
提交回复
热议问题