swift - 在 Swift 中查找父调用者文件、行号和函数
问题描述
我想打印调用者函数,但不确定如何做到这一点。#function
给出当前位置,但考虑一个通用方法formatError()
:
static func formatError(_ except: Error) -> String {
return "[\(tss()) \(#file).\(#line):\(#function)] ERROR: \(except.localizedDescription)"
}
#file
#line
and #function
only 告诉我们有关辅助方法的信息formatError()
——这没有帮助。
/Users/steve/git/cider/native/onsets/onsets/FileUtils.swift.94:formatError(_:)]
一个可行的解决方案是:
// Helper method
static func formatError(_ file: String, _ line: Int,
_ function: String, _ except: Error) -> String {
return "[\(tss()) \(file).\(line):\(function)] ERROR: \(except.localizedDescription)"
}
// Caller
formatError(#file, #line, #function, except)
结果:
/Users/steve/git/onsets/FileUtils.swift.110:writeFile(subDir:fname:data:)]
ERROR: The file “samples0514616_5359.dat” doesn’t exist.
但是每次都从调用者那里发送#file、#line、#function 是很尴尬的。有替代解决方案吗?
解决方案
您可以使用默认参数值。它看起来像这样:
func formatError(_ except: Error,
function: StaticString = #function,
file: StaticString = #file,
line: UInt = #line) -> String {
return "[\(file).\(line):\(function)] ERROR: \(except.localizedDescription)"
}
推荐阅读
- django - Django 2.1 测试问题
- python - 如何用户输入具有特定扩展名的文件名?
- r - 将字符串列表取消嵌套到单个字符串
- c++ - 有没有办法让两个不同大小的变量共享一个内存地址而不将它们声明为指针?
- java - bouncycastle jar 运行时异常
- microsoft-graph-api - ListJoinedTeams 是工作指定 /me,但没有工作指定 /user
- java - java - 更改对象后如何保持对象不变
- python - groupby 数据框和原始数据框之间的左合并带来外部合并
- data-structures - Mifare Classic 的制造商模块的组成是什么?
- javascript - 如何保存地理位置?