print(_:separator:terminator:)
separator
とterminator
を引数で持っている。
func print(
_ items: Any...,
separator: String = " ",
terminator: String = "\n"
)
- item: 出力する対象。
- separator: 各アイテムの間に出力する文字列。デフォルトは単一のスペース(” “)。
- terminator: 全てのアイテムが出力された後に出力する文字列。デフォルトは改行(“\n”)。
ここで、separator
は複数の値をitemに渡さないと反映されない点に注意。
for x in 10{
print(x, separator:"こんにちは")
// 1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n
// こんにちは は出力されない
}
print(1.0, 2.0, 3.0, 4.0, 5.0, separator:"こんにちは", terminator: "... ")
// // separated == "1.0こんにちは 2.0こんにちは 3.0こんにちは 4.0こんにちは 5.0... "
内部実装
public func print(
_ items: Any...,
separator: String = " ",
terminator: String = "\n"
) {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_print(items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_print(items, separator: separator, terminator: terminator, to: &output)
}
}
print(_:separator:terminator:to:)
func print<Target>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) where Target : TextOutputStream
- separator: 各アイテムの間に出力する文字列。デフォルトは単一のスペース(” “)。
- terminator: 全てのアイテムが出力された後に出力する文字列。デフォルトは改行(“\n”)。
- output: 各アイテムのテキスト表現を受け取る出力ストリーム。
______
to
パラメータを使用することで、出力先の変更をする。これにより、出力を別のストリーム、例えば文字列、ファイル、または他のデータ構造にリダイレクトできる。
var range = "My range: "
print(1...5, to: &range)
// range == "My range: 1...5\n"
// コンソールには何も出力されない
上記のコードスニペットでは、1…5 のテキスト表現が range という文字列に追加されている。print(_:separator:terminator:to:)
を呼び出す際、出力にはデフォルトで改行が含まれてしまうので、含めたくない場合は、別途terminator
として空の文字列を渡す必要が生じる。
for n in 1...5 {
print(n, terminator: "")
}
// Prints "12345"
内部実装
internal func _print<Target: TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_print_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
参考
print(_:separator:terminator:) | Apple Developer Documentation
Writes the textual representations of the given items into the standard output.
print(_:separator:terminator:to:) | Apple Developer Documentation
Writes the textual representations of the given items into the given output stream.