7

How do I recover the stack trace in Swift, so that I can find out which method was the last one called before a crash?

What I want to replicate in Swift is this method in C#:

public static Assembly GetComponentInInvocationDegree(int invocationDegree)
    {
        if (invocationDegree < 0) throw new ArgumentOutOfRangeException("Cannot set out of range value: invocation degree must be greater than or equal to zero");

        var stackInvocacion = new StackTrace().GetFrames();
        if (invocationDegree > 0)
        {
            int invokingAssemblyIndex = 0;
            string currentDegreeComponentName;
            try
            {
                for (int currentDegree = 0; currentDegree < invocationDegree; currentDegree++)
                {
                    currentDegreeComponentName = stackInvocacion[invokingAssemblyIndex].GetMethod().ReflectedType.Assembly.GetName().Name;
                    while (stackInvocacion[invokingAssemblyIndex].GetMethod().ReflectedType.Assembly.GetName().Name == currentDegreeComponentName) invokingAssemblyIndex++;                        
                }
            }
            catch (Exception ex) { throw new InvalidOperationException(string.Format("Cannot get component in invocation degree: invocation degree {0} does not exist", invocationDegree), ex); }

            return stackInvocacion[invokingAssemblyIndex].GetMethod().ReflectedType.Assembly;
        }

        return stackInvocacion[0].GetMethod().ReflectedType.Assembly;
    }
nhgrif
  • 60,018
  • 25
  • 128
  • 167
Holtrod
  • 105
  • 2
  • 7

2 Answers2

7

In many cases, you could use a try/catch mechanism.

do {
    try ... // risky business goes here
} catch let error as NSError {
    print("Error: \(error.domain)")
    println(NSThread.callStackSymbols())
}     
SwiftArchitect
  • 45,394
  • 26
  • 137
  • 173
2

In swift 3 and above, you can do it like this:

do {
    //....
}
catch {
    print("error occurred")
    print(Thread.callStackSymbols)
}
Rhythmic Fistman
  • 33,182
  • 5
  • 81
  • 149
david euler
  • 603
  • 8
  • 11