string - 有没有办法防止字符串在 Swift 中被插入?

标签 string swift logging string-interpolation

我正在尝试一个简单的记录器的想法,如下所示:

log(constant: String, _ variable: [String: AnyObject]? = nil)

使用方式如下:

log("Something happened", ["error": error])

但是我想防止滥用常量/变量模式,如下所示:

log("Something happened: \(error)") // `error` should be passed in the `variable` argument

有没有办法确保 constant 不是通过字符串插值构造的?

最佳答案

您可以使用StaticString而不是字符串:

func log(constant: StaticString, _ variable: [String: AnyObject]? = nil) {
    // You can retrieve `String` from `StaticString`
    let msg = constant.stringValue
}

let foo = 1
log("test \(foo)") // -> error: cannot invoke 'log' with an argument list of type '(String)'

关于string - 有没有办法防止字符串在 Swift 中被插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33224978/

相关文章:

asp.net - 我们可以记录 Bundle 错误吗?

javascript - 字符串包含另一个字符串

c - 使用循环替换字符串中的每个字母

c# - 如何将 HTML 值分配给 asp.net 字符串变量

arrays - Swift:如何按特定顺序将项目插入数组?

ios - 将自定义游戏逻辑添加到 Scene Kit (Swift)

ios - 创建 Swift AVAudioPlayer 错误

记录 SAS 脚本

c# - SourceContext 的 Serilog 记录器配置

c# - 如何从中获取日期字符串?