我可以在Swift中打印函数类型吗?

Fou*_*gsY 15 function ios swift

我想打印一个函数的类型.

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

printType(thanksTo)    // expected to print "Function (String) -> ()"
Run Code Online (Sandbox Code Playgroud)

Swift中有任何功能printType吗?

ndm*_*iri 30

Swift 3及更高版本

截至Swift 3,__FUNCTION__已被弃用.相反,用来#function代替__FUNCTION__.

(谢谢你,@ jovit.royeca.)


Swift 2.2及更早版本

你有几个选择:

  1. print(__FUNCTION__)functionName()如果函数没有参数,将输出.
  2. print(__FUNCTION__)functionName如果函数有一个或多个参数,则输出(不带括号).
  3. print(functionName.dynamicType)(() -> Swift.Int) -> Swift.Int为此假设函数输出:

    func functionName(closure: () -> Int) -> Int {
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

因此,要为您的printType功能实现所需的功能,您可以使用选项2和选项3的组合.


tym*_*mac 5

Swift 3有一个有趣的新印刷品,可以打印出你喂它的任何类型.它基本上打印代码完成中包含的相同信息.

print(type(of: functionName())) // prints the return type of a function
// Array<Float>
Run Code Online (Sandbox Code Playgroud)

这是来自Accelerate框架的卷积方法,具有一些属性.

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>>
Run Code Online (Sandbox Code Playgroud)

酷的东西!