Let’s say we have a Decodable
type User
.
struct User: Decodable {
let id: Int
let name: String
}
We have a JSON data that represents the User
type.
let jsonData = """
{
"id": 1,
"name": "John"
}
""".data(using: .utf8)!
We can decode the JSON data to User
type in Combine using decode(type:decoder:)
operator.
Just(jsonData)
.decode(type: User.self, decoder: JSONDecoder())
.sink { completion in
print(completion)
} receiveValue: { user in
print(user)
}
The complete code looks like this:
import Combine
import Foundation
struct User: Decodable {
let id: Int
let name: String
}
let jsonData = """
{
"id": 1,
"name": "John"
}
""".data(using: .utf8)!
Just(jsonData)
.decode(type: User.self, decoder: JSONDecoder())
.sink { completion in
print(completion)
} receiveValue: { user in
print(user)
}
When you run the above code, you will see the following output:
User(id: 1, name: "John")
finished