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)?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With