Diggory
(Diggory)
1
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.
Pippin
(Ethan Pippin)
2
You can have a parameter in a function with a default value of #function. However I don't find this very safe if wanting functions to be called from specific callers, that's what access is for (like you have found).
func caller() {
callee()
}
func callee(_ caller: String = #function) {
print(caller) // callee
}
1 Like