【问题标题】:Is there anyway to make log function? [duplicate]反正有没有做日志功能? [复制]
【发布时间】:2016-04-01 17:04:05
【问题描述】:

我想用一种方法打印#file#function#line

我尝试了以下代码,但问题就在这里。 无论我在哪里调用logm(),它总是打印logm 方法本身的信息,即使我将它声明为@inline

@inline(__always) func logm(items: Any...) {
    if let f = #file.componentsSeparatedByString("/").last {
        print("[\(f)][\(#function)][\(#line)]:", items)
    } else {
        print("[\(#function)][\(#line)]: ", items)
    }
}

有没有办法实现这种东西?为什么@inline 可以正常工作?

【问题讨论】:

  • 我投票决定重新提出这个问题,因为原来的“Swift 中的宏?”不是特别详细或与这个问题相似。答案可能相似,但上下文不同。
  • @jtbandes 谢谢。我仍然想知道为什么@inline 没有按预期工作。

标签: swift inline


【解决方案1】:

您可以将文件、行和函数作为参数传递,并将指令作为默认值:

func logm(items: Any..., file: String = #file, line: Int = #line, function: String = #function) {
    if let f = file.componentsSeparatedByString("/").last {
        print("[\(f)][\(function)][\(line)]:", items)
    } else {
        print("[\(function)][\(line)]: ", items)
    }
}

【讨论】:

  • 其实可变参数items必须是第一个,否则无法使用默认值。
  • 谢谢@Sulthan,我更新了我的答案。 @trick14,默认值允许您在不显式传递这些参数的情况下调用 logm
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2022-12-07
  • 2023-03-20
  • 1970-01-01
  • 2017-04-10
  • 2022-01-15
相关资源
最近更新 更多