iosswift

How to identify calling method from a called method in swift


here is a scenario

func callingMethod_A {
  self.someCalculation()
}

func callingMethod_B{
  self.someCalculation()
}

func someCalculation{
//how to find who called this method? is it callingMethod_A or _B at runtime?
//bla bla
}

how can we get the method name that called it during run time.
thank you.


Solution

  • I worked out a way to do this, for Swift code anyway:

    Define a String parameter callingMethod and give it a default value of #function. Do not pass anything from the caller and the compiler provides the calling function name.

    Building on @Anu.Krthik's answer:

    func someCalculation (parameter: String, callingMethod: String = #function ) {
     print("In `\(#function)`, called by `\(callingMethod)`")
    }
    
    func foo(string: String) {
        someCalculation(parameter: string)
    }
    
    foo(string: "bar")
    

    The above prints

    In `someCalculation(parameter:callingMethod:)`, called by `foo(string:)`
    

    Note that the output is the trimmed call name, eg,

    bringupGrid()

    rather than the internal callStackSymbols

    1   Blah Project, general.debug.dylib    0x0000000102bf1
    758 $s19PS_Project__general4MainC11bringupGridyyF + 1448

    (If you want to go back more than one call you will have to use callStackSymbols.)

    However, beware that this technique can be subverted if the caller provides a value for the callingMethod parameter. if you call it with:

    func foo(string: String) {
        someCalculation(parameter: string, callingMethod: "bogusFunctionName()")
    }
    

    You get the output

    In `someCalculation(parameter:callingMethod:)`, called by `bogusFunctionName()`
    

    instead.