標準エラーへの出力(Swift)

特にAHCでバグってしまった場合など、競プロに参加していると、標準エラーに文字列を出力したくなる場合があります。 以下のエクステンションを使うことで、print関数のto:パラメータに直接stderrを渡せるようになります。

extension UnsafeMutablePointer: TextOutputStream where Pointee == FILE {
    public mutating func write(_ string: String) {
        guard let data = string.data(using: .utf8) else { return }
        _ = data.withUnsafeBytes { bytes in
#if os(Linux)
            Glibc.write(fileno(self), bytes.baseAddress!, data.count)
#else
            Darwin.write(fileno(self), bytes.baseAddress!, data.count)
#endif
        }
    }
}

使い方は以下のように。

print("Hello, STDERR!", 1, 2, 3, 4, to: &stderr)

既出の内容ですが、print関数の自由度を損ないたくなかったので、stderrに生やしてみました。 どうぞご自由に。