Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print on stderr with Swift?

I'm using Swift 2.2 on Linux and I need to write some debug output on the standard error stream.

Currently, I'm doing the following:

import Foundation

public struct StderrOutputStream: OutputStreamType {
    public mutating func write(string: String) { fputs(string, stderr) }
}
public var errStream = StderrOutputStream()

debugPrint("Debug messages...", toStream: &errStream)

However, I've upgraded Swift to 2.2.1 but it seems that Foundation is no longer available.

How to write on the standard error stream with Swift 2.2.1 (and that'll still work on the next upgrade)?

like image 758
Maxime Chéramy Avatar asked May 16 '16 08:05

Maxime Chéramy


1 Answers

From https://swift.org/blog/swift-linux-port/:

The Glibc Module: Most of the Linux C standard library is available through this module similar to the Darwin module on Apple platforms.

So this should work on all Swift platforms:

#if os(Linux)
    import Glibc
#else
    import Darwin
#endif

public struct StderrOutputStream: OutputStreamType {
    public mutating func write(string: String) { fputs(string, stderr) }
}
public var errStream = StderrOutputStream()

debugPrint("Debug messages...", toStream: &errStream)

Update for Swift 3:

public struct StderrOutputStream: TextOutputStream {
    public mutating func write(_ string: String) { fputs(string, stderr) }
}
public var errStream = StderrOutputStream()

debugPrint("Debug messages...", to: &errStream) // "Debug messages..."
print("Debug messages...", to: &errStream)      // Debug messages...
like image 135
Martin R Avatar answered Nov 09 '22 04:11

Martin R