Github.com/agelessman/…

.encode and.decode are often used to encode and decode network response data, which are often used in real development. They can be understood as the mapping of data.

encode

Encode means encode, and in the figure above, we encode the Student object into Json data. .encode() receives a parameter that needs to implement the TopLevelEncoder protocol, because the TopLevelEncoder protocol implements the core methods of coding.

In development, we use JSONEncoder and PropertyListEncoder most often. Of course, you can also implement the TopLevelEncoder protocol yourself, which is beyond the scope of this article.

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

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

subject.send(Student(name: "Zhang", age: 20, score: 90))
Copy the code

Print result:

{"name":"Zhang"."age":20."score":90}
Copy the code

decode

Decode is just the reverse of encode, normally parsing Json data into a concrete object. .decode() receives a parameter required to implement the TopLevelEncoder protocol, because the TopLevelEncoder protocol implements the core method of coding.

In development, we use JSONEncoder and PropertyListEncoder most often. Of course, you can also implement the TopLevelEncoder protocol yourself, which is beyond the scope of this article.

The code is very similar to encode:

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

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

subject.send(Data("{\"name\":\"Zhang SAN\".\"age\": 20.\"score\": 90}".utf8))
Copy the code

Print result:

Student(name: "Zhang", age: 20, score: 90)
Copy the code