實例方法
decode(type:
decode(type:decoder:)
使用指定的解碼器對來自上遊的輸出進行解碼。
聲明
func decode<Item, Coder>(
type: Item.Type,
decoder: Coder
) -> Publishers.Decode<Self, Item, Coder> where Item : Decodable, Coder : TopLevelDecoder, Self.Output == Coder.Input
返回值
使用指定解碼器解碼給定類型並發布結果的發布者。
參數
type
要解碼為符合
Decodable
decoder
實現
TopLevelDecoder
協議的解碼器。
詳述
使用Publisher/decode(type:decoder:)
和
(或屬性列表的JSONDecoder
)來解碼從PropertyListDecoder
或使用URLSession.DataTaskPublisher
協議的其他數據源接收的數據。Decodable
在此示例中,PassthroughSubject
發布 JSON 字符串。 JSON 解碼器解析字符串,根據 Article
實現的
協議轉換其字段,並成功填充新的 Decodable
Article
。然後Publishers/Decode
發布者將Article
發布到下遊。如果解碼操作失敗(在源 JSON 字符串中數據丟失或格式錯誤的情況下發生),則流將終止並將錯誤傳遞給下遊訂閱者。
struct Article: Codable {
let title: String
let author: String
let pubDate: Date
}
let dataProvider = PassthroughSubject<Data, Never>()
cancellable = dataProvider
.decode(type: Article.self, decoder: JSONDecoder())
.sink(receiveCompletion: { print ("Completion: \($0)")},
receiveValue: { print ("value: \($0)") })
dataProvider.send(Data("{\"pubDate\":1574273638.575666, \"title\" : \"My First Article\", \"author\" : \"Gita Kumar\" }".utf8))
// Prints: ".sink() data received Article(title: "My First Article", author: "Gita Kumar", pubDate: 2050-11-20 18:13:58 +0000)"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Optional.Publisher debounce(for:scheduler:options:)用法及代碼示例
- Swift Optional.Publisher delay(for:tolerance:scheduler:options:)用法及代碼示例
- Swift Optional.Publisher drop(untilOutputFrom:)用法及代碼示例
- Swift Optional.Publisher reduce(_:_:)用法及代碼示例
- Swift Optional.Publisher tryDrop(while:)用法及代碼示例
- Swift Optional.Publisher breakpoint(receiveSubscription:receiveOutput:receiveCompletion:)用法及代碼示例
- Swift Optional.Publisher mapError(_:)用法及代碼示例
- Swift Optional.Publisher catch(_:)用法及代碼示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional.Publisher sink(receiveValue:)用法及代碼示例
- Swift Optional.Publisher scan(_:_:)用法及代碼示例
- Swift Optional.Publisher throttle(for:scheduler:latest:)用法及代碼示例
- Swift Optional.Publisher assertNoFailure(_:file:line:)用法及代碼示例
- Swift Optional.Publisher collect(_:)用法及代碼示例
- Swift Optional.Publisher combineLatest(_:_:_:_:)用法及代碼示例
- Swift Optional.Publisher share()用法及代碼示例
- Swift Optional.Publisher merge(with:_:_:)用法及代碼示例
- Swift Optional.Publisher map(_:_:)用法及代碼示例
- Swift Optional.Publisher assign(to:on:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:_:_:)用法及代碼示例
- Swift Optional.Publisher output(in:)用法及代碼示例
- Swift Optional.Publisher tryReduce(_:_:)用法及代碼示例
- Swift Optional.Publisher map(_:_:_:)用法及代碼示例
- Swift Optional.Publisher prepend(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Optional.Publisher decode(type:decoder:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。