here is a scenario
func callingMethod_A {
self.someCalculation()
}
func callingMethod_B{
self.someCalculation()
}
func someCalculation{
//how to find who
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.
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])
}