實例方法
encode(encoder:)
使用指定的編碼器對來自上遊的輸出進行編碼。
聲明
func encode<Coder>(encoder: Coder) -> Publishers.Encode<Self, Coder> where Coder : TopLevelEncoder
當
Output
符合 Encodable
時可用。返回值
使用指定編碼器對接收到的元素進行編碼並發布結果數據的發布者。
參數
encoder
實現
TopLevelEncoder
協議的編碼器。
詳述
使用 Publisher/encode(encoder:)
和
(或用於屬性列表的 JSONDecoder
)將 PropertyListDecoder
結構編碼為 Encodable
,該結構可用於生成 JSON 字符串(或作為二進製 plist 寫入磁盤)屬性清單的情況)。Data
在此示例中,PassthroughSubject
發布了 Article
。 Publisher/encode(encoder:)
運算符根據 Article
采用的
協議將 Codable
Article
結構的屬性編碼為新的 JSON 字符串。操作符將生成的 JSON 字符串發布給下遊訂閱者。如果編碼操作失敗(這可能發生在無法直接轉換為 JSON 的複雜屬性的情況下),則流終止並將錯誤傳遞給下遊訂閱者。
struct Article: Codable {
let title: String
let author: String
let pubDate: Date
}
let dataProvider = PassthroughSubject<Article, Never>()
let cancellable = dataProvider
.encode(encoder: JSONEncoder())
.sink(receiveCompletion: { print ("Completion: \($0)") },
receiveValue: { data in
guard let stringRepresentation = String(data: data, encoding: .utf8) else { return }
print("Data received \(data) string representation: \(stringRepresentation)")
})
dataProvider.send(Article(title: "My First Article", author: "Gita Kumar", pubDate: Date()))
// Prints: "Data received 86 bytes string representation: {"title":"My First Article","author":"Gita Kumar","pubDate":606211803.279603}"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher eraseToAnyPublisher()用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Result.Publisher print(_:to:)用法及代碼示例
- Swift Result.Publisher sink(receiveValue:)用法及代碼示例
- Swift Result.Publisher setFailureType(to:)用法及代碼示例
- Swift Result.Publisher first(where:)用法及代碼示例
- Swift Result.Publisher output(at:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
- Swift Result.Publisher drop(while:)用法及代碼示例
- Swift Result.Publisher prefix(_:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher merge(with:_:)用法及代碼示例
- Swift Result.Publisher map(_:)用法及代碼示例
- Swift Result.Publisher append(_:)用法及代碼示例
- Swift Result.Publisher breakpointOnError()用法及代碼示例
- Swift Result.Publisher handleEvents(receiveSubscription:receiveOutput:receiveCompletion:receiveCancel:receiveRequest:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher encode(encoder:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。