Swift:打印存储在变量中的函数的名称 [英] Swift: Print name of a function stored in a variable

查看:70
本文介绍了Swift:打印存储在变量中的函数的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例:

let plus: (Int, Int) -> Int = (+)
print(plus)
debugPrint(plus)

print(UIView.removeFromSuperview)
debugPrint(UIView.removeFromSuperview)

print(UnsafePointer<Int>.distance(to:))
debugPrint(UnsafePointer<Int>.distance(to:))

打印无用的输出:

(功能)
(功能)
(功能)
(功能)
(功能)
(功能)

(Function)
(Function)
(Function)
(Function)
(Function)
(Function)

有什么方法可以在Swift中获取函数的名称吗?是不是当前正在运行的函数的名称( #funciton ).但是存储在变量或类函数等中的函数的名称.每种语言,特别是假装为函数性的语言,都应该具有这种能力,对吗?

Is there any way to get function's name in Swift? I mean, not the name of the function which is currently running (#funciton). But the name of a function stored in a variable, or a class function etc. Every language, especially that pretending to be functional, should have such an ability, right?

推荐答案

Swift是一种静态调度的编程语言.这导致Swift在需要调用函数时会尽可能多地使用内存地址.副作用是无法捕获被调用的函数名,因为在大多数情况下,这将是一个简单的内存地址.

Swift is a statically dispatched programming language. This results in Swift using memory addresses as much as possible when it needs to call a function. The side effect is the inability to capture the called function name, since in most of the cases it will be a simple memory address.

#function 之所以起作用,是因为在编译时,该构造被调用者函数(不是运行时构造)替换.

#function works because this the construct gets replaced at compile time by the caller function (it's not a runtime construct).

如果有可用的调试符号,则可以从二进制地址重构函数名称,但是这将需要从应用程序内部访问dSYM基础结构,这不太可能因为您需要运送而已应用程序以及调试符号,这是黑客邀请您对应用程序进行逆向工程的原因.

If you have the debug symbols available, you could reconstruct the function name from a binary address, however this would require access to the dSYM infrastructure from within your application, which it's unlikely that you'll want to do, since shipping you app along with the debug symbols is an invitation for hackers to reverse engineer with your app.

动态分派的语言(例如Objective-C)保留对被调用函数(选择器)的引用,但前提是被调用函数是方法(即成员函数).其他语言(例如Ruby,JavaScript)是解释性语言,这使得函数名称始终可用.

Dynamically dispatched languages, like Objective-C, keep a reference to the called function (selector), but only if the called function is a method (i.e. a member function). Other languages, like Ruby, JavaScript, are interpreted languages, which makes the function name available at all times.

这篇关于Swift:打印存储在变量中的函数的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆