print() to standard error has "[" prefix?

Using Xcode 9.3 to create a Swift command line program now (didn't try with any other version). I'm seeing a "[" prefix and "]" suffix for each line if I print to standard error in a function I created, but NOT when I do it directly. See the different outputs as a "#" comment on the two print lines:


struct StderrOutputStream: TextOutputStream {
    mutating func write(_ string: String) { fputs(string, stderr) }
}
var errStream = StderrOutputStream()
func fprint(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    print(_: items, separator: separator, terminator: terminator, to: &errStream)
}
print("Usage: sal option [args]", to: &errStream)   # Usage: sal option [args]
fprint("Usage: sal option [args]")                  # ["Usage: sal option [args]"]


Why does embedding 'print' in my own function generate these two extra characters?

Accepted Reply

Actually, that's right. This declaration:


func fprint(_ items: Any..., separator: String = " ", terminator: String = "\n")


is basically equivalent to this declaration:


func fprint(_ items: [Any], separator: String = " ", terminator: String = "\n")


except that you don't need to write the [ … ] enclosing the list of arguments at the call site. Joining the array elements like a reasonable thing to do.

Replies

Interestingly enough, using the code below makes the [] go away:


    let str = items.map{String(describing: $0)}.joined(separator: " ")
    print(str, terminator: terminator, to: &errStream)


I guess the way it was originally written, the items gets passed as an array?

Actually, that's right. This declaration:


func fprint(_ items: Any..., separator: String = " ", terminator: String = "\n")


is basically equivalent to this declaration:


func fprint(_ items: [Any], separator: String = " ", terminator: String = "\n")


except that you don't need to write the [ … ] enclosing the list of arguments at the call site. Joining the array elements like a reasonable thing to do.