協議
Text
TextOutputStream
可以作為text-streaming 操作目標的類型。
聲明
protocol TextOutputStream
概述
您可以將標準庫的 print(_:to:)
和 dump(_:to:)
函數的輸出發送到符合 TextOutputStream
協議的類型的實例,而不是標準輸出。 Swift 的String
類型已經符合TextOutputStream
,因此您可以在字符串中捕獲來自print(_:to:)
和dump(_:to:)
的輸出,而不是將其記錄到標準輸出中。
var s = ""
for n in 1...5 {
print(n, terminator: "", to: &s)
}
// s == "12345"
符合TextOutputStream 協議
要使您的自定義類型符合TextOutputStream
協議,請實現所需的write(_:)
方法。使用TextOutputStream
目標的函數可以在每次寫入操作時多次調用write(_:)
。
例如,這是一個輸出流的實現,它將任何輸入轉換為其純 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: "")
}
}
ASCIILogger
類型的 write(_:)
方法通過轉義每個 Unicode 標量來處理其字符串輸入,但 "\n"
行返回除外。通過將 print(_:to:)
函數的輸出發送到 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}"
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift ThrowingTaskGroup prefix(while:)用法及代碼示例
- Swift TaskGroup max()用法及代碼示例
- Swift ThrowingTaskGroup max(by:)用法及代碼示例
- Swift TaskGroup filter(_:)用法及代碼示例
- Swift ThrowingTaskGroup prefix(_:)用法及代碼示例
- Swift ThrowingTaskGroup compactMap(_:)用法及代碼示例
- Swift TaskGroup contains(where:)用法及代碼示例
- Swift ThrowingTaskGroup next()用法及代碼示例
- Swift TaskGroup allSatisfy(_:)用法及代碼示例
- Swift ThrowingTaskGroup first(where:)用法及代碼示例
- Swift TaskGroup prefix(_:)用法及代碼示例
- Swift ThrowingTaskGroup dropFirst(_:)用法及代碼示例
- Swift TaskGroup contains(_:)用法及代碼示例
- Swift TaskGroup reduce(_:_:)用法及代碼示例
- Swift TaskPriority init(rawValue:)用法及代碼示例
- Swift TaskGroup flatMap(_:)用法及代碼示例
- Swift TaskPriority ...(_:)用法及代碼示例
- Swift ThrowingTaskGroup.Iterator用法及代碼示例
- Swift ThrowingTaskGroup map(_:)用法及代碼示例
- Swift TaskGroup next()用法及代碼示例
- Swift ThrowingTaskGroup allSatisfy(_:)用法及代碼示例
- Swift TaskGroup.Iterator用法及代碼示例
- Swift ThrowingTaskGroup contains(where:)用法及代碼示例
- Swift ThrowingTaskGroup contains(_:)用法及代碼示例
- Swift TaskLocal用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 TextOutputStream。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。