实例方法
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:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。