ios - 如何在swift中从被调用方法中识别调用方法

标签 ios swift

这是一个场景

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
}

我们怎样才能得到在运行时调用它的方法名。
谢谢。

最佳答案

我想出了一个方法来做到这一点,不管怎样,对于 Swift 代码:

定义一个String 参数callingFunction 并给它一个默认值#function。不要从调用者传递任何内容,编译器会提供调用函数名称。

基于@Anu.Krthik 的回答:

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 参数提供值,则可能会破坏此技术。如果你调用它:

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

你得到输出

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

相反。

关于ios - 如何在swift中从被调用方法中识别调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53208339/

相关文章:

string - '(NSObject, AnyObject )' is not convertible to ' 字符串'

ios - 登录窗口不会在下一个 View Controller Swift 中打开

ios - 在 Spritekit 中左右倾斜宇宙飞船

ios - 核心数据如何更新一条记录?

android - 在同一代码库中使用 Android 和 iOS 代码编写 React Native?

ios - 如何复制带 child 的 SKNodes

ios - 声明 NSDictionary 并将其放入 Swift 中的键值对?

ios - 用于自定义 TableViewCell 的 MvvmCross iOS SelectedCommand

ios - 拦截iOS中的来电(未接听状态)

ios - UIAppearance 代理规则何时应用于新的 View Controller ?