Can I print function type in Swift? Can I print function type in Swift? swift swift

Can I print function type in Swift?


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.


Swift 3 has an interesting new print which prints the type of anything you feed it. It basically prints the same info that is contained in the Code Completion.

print(type(of: functionName())) // prints the return type of a function// Array<Float>

Here is a convolution method from the Accelerate framework with some properties.

vDSP_conv(newXin, 1, kernel.reversed(), 1, &res, 1, vDSP_Length(T), vDSP_Length(N))print(type(of: vDSP_conv)) // prints the method arguments.// ((UnsafePointer<Float>, Int, UnsafePointer<Float>, Int, UnsafeMutablePointer<Float>, Int, UInt, UInt)) -> ()print(type(of: kernel)) // prints the property type.// Array<Float>print(type(of: kernel.reversed())) // prints the property type and method type from the Swift Standard Library.// ReversedRandomAccessCollection<Array<Float>>

Cool stuff!


It's now print(#function) in Xcode 7.3.1

Refer to the release notes for swift at the below location.

https://github.com/apple/swift/blob/master/CHANGELOG.md

The change happened in Swift 2.2

enter image description here