實例方法
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 Result.Publisher debounce(for:scheduler:options:)用法及代碼示例
- Swift Result.Publisher delay(for:tolerance:scheduler:options:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher drop(while:)用法及代碼示例
- Swift Result.Publisher drop(untilOutputFrom:)用法及代碼示例
- 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 eraseToAnyPublisher()用法及代碼示例
- Swift Result.Publisher setFailureType(to:)用法及代碼示例
- Swift Result.Publisher first(where:)用法及代碼示例
- Swift Result.Publisher output(at:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
- Swift Result.Publisher prefix(_:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher merge(with:_:)用法及代碼示例
- Swift Result.Publisher map(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher decode(type:decoder:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。