func write(String)
Overview 概要
You can send the output of the standard library’s print(_:
and dump(_:
functions to an instance of a type that conforms to the Text
protocol instead of to standard output. Swift’s String
type conforms to Text
already, so you can capture the output from print(_:
and dump(_:
in a string instead of logging it to standard output.
あなたは、標準ライブラリのprint(_:
およびdump(_:
関数の出力をText
プロトコルに準拠する型のインスタンスに送ることが、標準出力に送る代わりに行えます。SwiftのString
型は、すでにText
に準拠します、なのであなたはprint(_:
およびdump(_:
からの出力を文字列の中に捕えることが、それを標準出力に記録する代わりに行えます。
var s = ""
for n in 1...5 {
print(n, terminator: "", to: &s)
}
// s == "12345"
Conforming to the TextOutputStream Protocol TextOutputStreamプロトコルに準拠する
To make your custom type conform to the Text
protocol, implement the required write(_:)
method. Functions that use a Text
target may call write(_:)
multiple times per writing operation.
あなたのあつらえのクラスをText
プロトコルに準拠させるには、必須write(_:)
メソッドを実装してください。Text
ターゲットを使う関数は、write(_:)
を書き込み操作のたびに複数回呼び出すでしょう。
As an example, here’s an implementation of an output stream that converts any input to its plain ASCII representation before sending it to standard output. 一例として、ここに出力ストリームの実装があります、それは何らかの入力を標準出力に送る前にそれの標準ASCII表現に変換します。
struct ASCIILogger: TextOutputStream {
mutating func write(_ string: String) {
let ascii = string.unicodeScalars.lazy.map { scalar in
scalar == "\n"
? "\n"
: scalar.escaped(asASCII: true)
}
print(ascii.joined(separator: ""), terminator: "")
}
}
The ASCIILogger
type’s write(_:)
method processes its string input by escaping each Unicode scalar, with the exception of "\n"
line returns. By sending the output of the print(_:
function to an instance of ASCIILogger
, you invoke its write(_:)
method.
ASCIILogger
型のもつwrite(_:)
メソッドは、それの文字列入力を各ユニコードスカラーをエスケープすることによって処理します、"\n"
行復帰を除いては。print(_:
関数の出力をASCIILogger
のインスタンスに送ることによって、あなたはそれのwrite(_:)
メソッドを発動します。
let s = "Hearts ♡ and Diamonds ♢"
print(s)
// Prints "Hearts ♡ and Diamonds ♢"
var asciiLogger = ASCIILogger()
print(s, to: &asciiLogger)
// Prints "Hearts \u{2661} and Diamonds \u{2662}"