Hello,
The other day I was designing a class that was a singleton and wanted to have a warning printed if anyone called its init()
except for that class itself. I then realised that I could simply mark the init()
as private
, which was very useful. Problem solved.
However, I still was curious about how I could have solved the problem if the solution wasn't available and that lead me to wonder if it's possible to get the name of the caller of a function. e.g.
func caller() {
print("I am the caller")
print("function: \(#function)")
callee()
}
func callee() {
print("I am the callee")
print("function: \(#function)")
print("Caller: \(someWayToGetTheNameOfTheCaller())")
let origin = Thread.callStackSymbols
print(origin[0])
}
caller()
I found from a cursory Google that Thread.callStackSymbols()
exists, but that provides an array of Strings which contain the memory address of the caller.
e.g.
0 ??? 0x0000000100728904 0x0 + 4302473476
Is there a way to get the actual name of the calling function?
This is just out of curiosity. I don't require this functionality, but I find it interesting.
Thanks.