Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I print function type in Swift?

I want to print the type of a function.

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

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

Is there any function in Swift that behaves like printType?

like image 712
FourwingsY Avatar asked Jul 12 '15 06:07

FourwingsY


Video Answer


1 Answers

Swift 3 and later

As of Swift 3, __FUNCTION__ is deprecated. Instead, use #function in place of __FUNCTION__.

(Thank you, @jovit.royeca.)


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.

like image 193
ndmeiri Avatar answered Oct 07 '22 00:10

ndmeiri