FourwingsY FourwingsY - 6 months ago 3x
Swift Question

Can I print function type in Swift?

I want to check the type of function

func thanksTo(name: String) {
print("Thanks, \(name)")

printType(thanksTo) // expected to print "Function (String) -> ()"

Is there any function like this


Swift 3

As of Swift 3, __FUNCTION__ is deprecated. (Thank you @jovit.royeca.) Instead, use #function in place of __FUNCTION__.

Swift 2.2 and Earlier

You have a few options:

  1. print(__FUNCTION__) will output functionName() if the function has no arguments.
  2. print(__FUNCTION__) will output functionName (without parentheses) if the function has one or more arguments
  3. print(functionName.dynamicType) will output (() -> Swift.Int) -> Swift.Int for this hypothetical function:

    func functionName(closure: () -> Int) -> Int {

Thus, to implement the desired functionality for your printType function, you could use a combination of Option 2 and Option 3.