Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: determine what object called a function?

Tags:

swift

I am writing some Swift code and I would like to know the class of the object that called the function. I don't want to pass in any parameters. From within the function I want to be able to know who called it.

Any suggestion?

like image 696
zumzum Avatar asked Mar 10 '15 00:03

zumzum


3 Answers

If you want to do that using Swift, you can do this:

func debug(file: String = #file, line: Int = #line, function: String = #function) -> String {
    return "\(file):\(line) : \(function)"
}
like image 52
Abner Terribili Avatar answered Oct 13 '22 17:10

Abner Terribili


To access the underlying class of a method from within itself, use the dynamicType property:

 self.dynamicType

If you want to know the origin of the original call, you can use NSThread to return debugging information about the stack:

 NSThread.callStackSymbols()

This method returns a descriptive array of values that you're used to seeing when exceptions are thrown. The strings represent a backtrace of all current activity on your call stack.

I don't want to be presumptuous, but it seems to me that outside of debugging, there isn't a good reason, conceptually, at least, to know the origin of a specific method call for any and every function. If you need to retrieve the class Type of the last method call on the stack, why not implement an interface that lets you access this information through a straightforward route?

like image 20
kellanburket Avatar answered Oct 13 '22 19:10

kellanburket


You can use following template to know from which file, line number in file, and function this someFunction is called:

func someFunction(file: String = #file, line: Int = #line, function: String = #function)
{
    NSLog("\(file.lastPathComponent):\(line) : \(function)")
}
like image 17
gagarwal Avatar answered Oct 13 '22 19:10

gagarwal