Search code examples
swiftvapor

'String' does not conform to expected type 'CVarArg'


When I'm trying to log using NSLog, I'm facing this error:

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

Here is my code:

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

Why does this happen and how can I fix it?


Solution

  • NSLog takes as the first argument a format string, which is followed by a list of arguments, which are substituted for the placeholders in the format string (compare String Format Specifiers).

    On Apple platforms, you can print a String using the %@ format:

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

    However, this does not work on Linux platforms (such as Vapor). Here you have to convert the Swift string to a C string in order to pass it as an argument to NSLog (and use the %s format for C strings):

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