首页 > 解决方案 > 在 Swift 中查找父调用者文件、行号和函数

问题描述

我想打印调用者函数,但不确定如何做到这一点。#function给出当前位置,但考虑一个通用方法formatError()

static func formatError(_ except: Error) -> String {
    return "[\(tss()) \(#file).\(#line):\(#function)] ERROR: \(except.localizedDescription)"
}

#file #lineand #functiononly 告诉我们有关辅助方法的信息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 是很尴尬的。有替代解决方案吗?

标签: swiftexception

解决方案


您可以使用默认参数值。它看起来像这样:

func formatError(_ except: Error,
    function: StaticString = #function,
    file: StaticString  = #file,
    line: UInt  = #line) -> String {
    return "[\(file).\(line):\(function)] ERROR: \(except.localizedDescription)"
}

推荐阅读