当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift Optional.Publisher decode(type:decoder:)用法及代码示例


实例方法

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+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Optional.Publisher decode(type:decoder:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。