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

标签 ios swift function

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

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

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

Swift 中是否有任何函数的行为类似于 printType

最佳答案

Swift 3 及更高版本

从 Swift 3 开始,__FUNCTION__ 已弃用。相反,使用 #function 代替 __FUNCTION__

(谢谢@jovit.royeca。)


Swift 2.2 及更早版本

您有几个选择:

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

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

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

关于ios - 我可以在 Swift 中打印函数类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31365097/

相关文章:

ios - 当界面方向颠倒时呈现 View Controller

ios - 在 Swift 中重新加载表数据?

ios - 如何在 Xcode 中设置启动屏幕图像

optimization - 使用 "if let"解包堆栈对象(例如结构)

c# - 42883 : function does not exist - Calling Postgres Functions in Entity Framework C# Npgsql

c++ - 编译器提示 "Error: stray '\24 0' in program"

c++ - 合法功能参数

ios - 在 UIView 的 -drawRect : method 中绘制彩色文本

ios - Objective C - 滑动以从主屏幕打开应用程序

iPhone 上的 jquery 移动网站