简体   繁体   English

如何使用Swift在stderr上打印?

[英]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. 我在Linux上使用Swift 2.2,我需要在标准错误流上编写一些调试输出。

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. 但是,我已将Swift升级到2.2.1,但似乎Foundation已不再可用。

How to write on the standard error stream with Swift 2.2.1 (and that'll still work on the next upgrade)? 如何使用Swift 2.2.1在标准错误流上编写(并且仍然可以在下一次升级时使用)?

From https://swift.org/blog/swift-linux-port/ : 来自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. Glibc模块:大多数Linux C标准库都可通过此模块获得,类似于Apple平台上的Darwin模块。

So this should work on all Swift 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)

Update for Swift 3: 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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM