19

I am looking to get the name of function in swift.

I basically want something like

__FUNCTION__

but from a different function e.g.

func do () {
   code etc
}

func doStuff () {
   var funcName = do().name
}

the above would be perfect.

Any ideas?

2
  • Could you please explain the use case? Why do you need that? Commented Jun 17, 2017 at 9:47
  • One use case is runtime generated and compiled code. Being able to get a function name at runtime allows for more compile-time checks. Commented Sep 28, 2021 at 22:44

3 Answers 3

27

#function might be what you want.

print(#function)

class Log {
    func info(_ info: String, funcName: String = #function) {}
}
Sign up to request clarification or add additional context in comments.

Comments

5

In Swift 3 the right keyword is #function. You could pass a pointer to a String object which is used to store the function name. For example:

func myFunction(param1:Any, param2:Any, functionName: UnsafeMutablePointer<String>?) -> Any {
    if functionName != nil { 
        functionName.pointee = #function 
    }
    ...
}

Usage:

var name:String 
// You can always pass nil if you are not interested in retrieving the 
// function name
let result = myFunction(1, 2, functionName: &name) 
print(name)

Comments

1

Not the cleanest, but it works.

func dost () -> (name: String,String) {
    return (__FUNCTION__,"")
}

func doStuff () {
    var funcName = dost().name
}

You could aways just return the function name without the tuple.

4 Comments

I arrived at something similar func dostuff(getName: Bool) -> String {if (getName) return __FUNCTION__ } but I was wondering if there was something nicer maybe
Note: in Swift 3 it has been replaced with #function.
@RamyAlZuhouri Thanks! If you make your comment to an answer, it could be accepted, and the question could be closed.
Ok I elaborated it a bit and made it an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.