Combine操作符Encoding and decoding示例


3个月前 136次点击 来自 移动端

标签: Swift

Encoding and decoding

.encode和.decode经常用于对网络响应数据的编码和解码

encode

struct Student: Codable {
    let name: String
    let age: Int
    let score: Int
}

let subject = PassthroughSubject<Student, Never>()
let cancellable = subject
    .encode(encoder: JSONEncoder())
    .map {
        String(data: $0, encoding: .utf8)
    }
    .sink(receiveCompletion: {
        print($0)
    }, receiveValue: { someValue in
        print(someValue ?? "")
    })

subject.send(Student(name: "A", age: 20, score: 90))

decode

struct Student: Codable {
    let name: String
    let age: Int
    let score: Int
}

let subject = PassthroughSubject<Data, Never>()
let cancellable = subject
    .decode(type: Student.self,
            decoder: JSONDecoder())
    .sink(receiveCompletion: {
        print($0)
    }, receiveValue: { someValue in
        print(someValue)
    })

subject.send(Data("{\"name\":\"A\",\"age\":20,\"score\":90}".utf8))

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1