我正在尝试一个简单的记录器的想法,如下所示:
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/