How to identify calling method from a called method in swift

后端 未结 2 1407
刺人心
刺人心 2021-01-23 08:20

here is a scenario

func callingMethod_A {
  self.someCalculation()
}

func callingMethod_B{
  self.someCalculation()
}

func someCalculation{
//how to find who          


        
相关标签:
2条回答
  • 2021-01-23 08:41

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

    Define a String parameter callingFunction 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:)`
    

    However, beware that this technique can be subverted if the caller provides a value for the callingFunction 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.

    0 讨论(0)
  • 2021-01-23 08:55

    You can use Thread.callStackSymbols like this

    func callingMethod_A() {
        self.someCalculation()
    }
    
    func callingMethod_B(){
        self.someCalculation()
    }
    
    func someCalculation(){
        let origin = Thread.callStackSymbols
        print(origin[0])
        print(origin[1])
    }
    
    0 讨论(0)
提交回复
热议问题