How to identify calling method from a called method in swift

后端 未结 2 1406
刺人心
刺人心 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.

提交回复
热议问题