How to print on stderr with Swift?

I use Swift 2.2 on Linux, and I need to write some debugging output in a standard error stream.

I am currently 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 upgraded Swift to version 2.2.1, but it seems that it is Foundationno longer available.

How to record a standard error stream with Swift 2.2.1 (and this will still work the next update)?

+4
source share
1 answer

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

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

, Swift:

#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)

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...
+5

All Articles