Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine which object/class is calling a global Swift function?

Tags:

swift

With this code:

func externalFunc() {
    println("How can I know which object/class is calling me?")
}

class Test {
    func callExternalFunc() {
        externalFunc()
    }
}

In the Objective-C runtime objc_msgSend passes two hidden parameters to every message we send. They are self and _cmd. (Source)

In the above example, is there any way to know who is calling externalFunc?

like image 657
Diego Freniche Avatar asked Feb 10 '15 17:02

Diego Freniche


2 Answers

I'm not sure if there is a way to obtain this automatically, but you can get this info if you add a default param of type String to the function and set it to #function.

For example...

func externalFunc(callingFunctionName: String = #function) {
    println("Calling Function: \(callingFunctionName)")
}

Then you would call it without the added default param...

let test = Test()
test.callExternalFunc()

And it would print the following...

"Calling Function: callExternalFunc()"
like image 58
Jawwad Avatar answered Apr 29 '23 13:04

Jawwad


If you are willing to modify the method signature you could do something like below:

func externalFunc(file: String = #file, line: Int = #line) {
    print("calling File:\(file) from Line:\(line)")
}

From apple's swift blog

Swift borrows a clever feature from the D language: these identifiers (__FILE__ & __LINE__ ) expand to the location of the caller when evaluated in a default argument list.

Note that __FILE__ and __LINE__ have been depreciated in Swift 2.2 and have been removed in Swift 3. They are replaced by #file, and #line.

like image 34
PixelCloudSt Avatar answered Apr 29 '23 12:04

PixelCloudSt