【问题标题】:'String' does not conform to expected type 'CVarArg'“字符串”不符合预期的类型“CVarArg”
【发布时间】:2017-07-28 23:27:12
【问题描述】:

当我尝试使用NSLog 登录时,我遇到了这个错误:

remote: /tmp/build_f459d376d1bc10ac2e93e52575ac5ea9/Sources/App/main.swift:368:49: error: argument type 'String' does not conform to expected type 'CVarArg'
remote:                     NSLog("FILE NOT AVAILABLE", "TESTNOTI")
remote:                                                 ^~~~~~~~~~
remote:                                                            as! CVarArg

这是我的代码:

if fileManager.fileExists(atPath: (drop.config["servers", "default", "KeyURL"]?.string ?? "default")) {
    NSLog("FILE AVAILABLE", "TESTNOTI")
} else {
    NSLog("FILE NOT AVAILABLE", "TESTNOTI")
}

为什么会发生这种情况,我该如何解决?

【问题讨论】:

  • 分享几行代码。
  • 错误信息中的as! CVarArg来自哪里?它不在代码中。除此之外,在 NSLog 中使用两个参数而不使用任何占位符 (%@)

标签: swift vapor


【解决方案1】:

您似乎正在使用 Vapor 框架,我引用:

并非所有核心库(Foundation)都可在 Linux 上使用。

您在 Vapor 上创建的问题已经得到了答案: https://github.com/vapor/vapor/issues/870

【讨论】:

    【解决方案2】:

    NSLog 格式字符串作为第一个参数, 随后 由参数列表代替占位符 在格式字符串中(比较String Format Specifiers)。

    在 Apple 平台上,您可以使用%@ 格式打印String

    let fileName = "the file"
    NSLog("File not found: %@", fileName)
    

    但是,这不适用于 Linux 平台(例如 Vapor)。 在这里,您必须将 Swift 字符串转换为 C 字符串才能通过 它作为 NSLog 的参数(并对 C 字符串使用 %s 格式):

    let fileName = "the file"
    fileName.withCString {
        NSLog("File not found: %s", $0)
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2018-12-30
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多