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