如何快速识别被调用方法中的调用方法 [英] How to identify calling method from a called method in swift

查看:87
本文介绍了如何快速识别被调用方法中的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个场景

func callingMethod_A {
  self.someCalculation()
}

func callingMethod_B{
  self.someCalculation()
}

func someCalculation{
//how to find who called this method? is it callingMethod_A or _B at runtime?
//bla bla
}

我们如何获得在运行时调用它的方法名称.
谢谢.

how can we get the method name that called it during run time.
thank you.

推荐答案

无论如何我都为Swift代码设计了一种方法:

I worked out a way to do this, for Swift code anyway:

定义String参数callingFunction,并将其默认值设置为#function.不要传递任何来自调用方的信息,编译器会提供调用函数的名称.

Define a String parameter callingFunction and give it a default value of #function. Do not pass anything from the caller and the compiler provides the calling function name.

以@ Anu.Krthik的答案为基础:

Building on @Anu.Krthik's answer:

func someCalculation (parameter: String, callingMethod: String = #function ) {
 print("In `\(#function)`, called by `\(callingMethod)`")
}

func foo(string: String) {
    someCalculation(parameter: string)
}

foo(string: "bar")

上面的照片

In `someCalculation(parameter:callingMethod:)`, called by `foo(string:)`

但是,请注意,如果调用方为callingFunction参数提供值,则可以颠覆该技术.如果您使用以下方式调用它:

However, beware that this technique can be subverted if the caller provides a value for the callingFunction parameter. if you call it with:

func foo(string: String) {
    someCalculation(parameter: string, callingMethod: "bogusFunctionName()")
}

您将获得输出

In `someCalculation(parameter:callingMethod:)`, called by `bogusFunctionName()`

相反.

这篇关于如何快速识别被调用方法中的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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