How to print on stderr with Swift?

无人久伴 提交于 2019-12-22 08:05:35

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/37249787/how-to-print-on-stderr-with-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!