简体   繁体   English

我可以在Swift中打印功能类型吗?

[英]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 ? Swift中有没有像printType一样的printType

Swift 3 and later Swift 3及更高版本

As of Swift 3, __FUNCTION__ is deprecated. 从Swift 3开始,不推荐使用__FUNCTION__ Instead, use #function in place of __FUNCTION__ . 相反,使用#function代替__FUNCTION__

(Thank you, @jovit.royeca.) (谢谢你,@ jovit.royeca。)


Swift 2.2 and earlier Swift 2.2及更早版本

You have a few options: 你有几个选择:

  1. print(__FUNCTION__) will output functionName() if the function has no arguments. 如果函数没有参数, print(__FUNCTION__)将输出functionName()
  2. print(__FUNCTION__) will output functionName (without parentheses) if the function has one or more arguments. 如果函数有一个或多个参数, print(__FUNCTION__)将输出functionName (不带括号)。
  3. print(functionName.dynamicType) will output (() -> Swift.Int) -> Swift.Int for this hypothetical function: print(functionName.dynamicType)将为此假设函数输出(() -> Swift.Int) -> Swift.Int

     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. 因此,要为printType函数实现所需的功能,可以使用选项2和选项3的组合。

Swift 3 has an interesting new print which prints the type of anything you feed it. Swift 3有一个有趣的新印刷品,可以打印出你喂它的任何类型。 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. 这是来自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>>

Cool stuff! 酷的东西!

试试这个

println(thanksTo.dynamicType)

It's now print(#function) in Xcode 7.3.1 它现在在Xcode 7.3.1中打印(#function)

Refer to the release notes for swift at the below location. 请参阅以下位置的swift发行说明。

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

The change happened in Swift 2.2 这种变化发生在Swift 2.2中

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM