如何使用Swift在stderr上打印? [英] How to print on stderr with Swift?
问题描述
我在Linux上使用Swift 2.2,我需要在标准错误流上写一些调试输出.
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)
但是,我已经将Swift升级到2.2.1,但似乎Foundation
不再可用.
However, I've upgraded Swift to 2.2.1 but it seems that Foundation
is no longer available.
如何使用Swift 2.2.1在标准错误流上编写代码(并且在下一次升级中仍然可以使用)?
How to write on the standard error stream with Swift 2.2.1 (and that'll still work on the next upgrade)?
推荐答案
来自 https://swift.org/blog/swift-linux-port/:
Glibc模块:与Linux平台上的Darwin模块类似,大多数Linux C标准库可通过此模块获得.
The Glibc Module: Most of the Linux C standard library is available through this module similar to the Darwin module on Apple platforms.
所以这应该在所有Swift平台上都可以使用:
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)
针对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...
这篇关于如何使用Swift在stderr上打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!