将String转换为StaticString

Van*_*nya 10 string swift

在Swift 3.0中是否有办法StaticStringString复杂的类型中获取类型?

示例(需要转换才能工作):

let aString: StaticString = "One part" + "Second part"
Run Code Online (Sandbox Code Playgroud)

Mic*_*ner 8

这是不可能的,因为a StaticString被定义为

一个简单的字符串,用于表示“在编译时已知”的文本。(参考

字符串连接在运行时发生。

我不知道您打算做什么,但是您可以执行以下操作:

func aMethod(i: Int) -> StaticString {
    switch i {
    case 0:
        return "Simple"
    case 1:
        return "Complex"
    default:
        return "Default"
    }
}
let result = aMethod(i: 1)
print("\(type(of: result)): \(result)") // prints "StaticString: Complex"
Run Code Online (Sandbox Code Playgroud)

  • 谢谢迈克尔,但我真的对进行这种转换的通用黑客方式很感兴趣。 (2认同)

Alf*_*lfa 8

您可以使用格式说明符,例如%d%s 例如:

os_log("Successfully fetched %d recordings.", type: .info, count)
os_log("Getting recordings from %s.",
  type: .info, url.absoluteString)
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请点击此处


sup*_*org 5

根据您的实际用例,您可能有一些方法来解决它。例如,如果您正在处理os_log,则可以使用%@if 您想使用 SwiftString而不是CVarArg

//os_log("Compiler error with: \(string).", log: log)
os_log("This is OK: %@.", log: log, string)
Run Code Online (Sandbox Code Playgroud)