Codeable is a type alias for the Encodable and Decodable protocols. It can be used to Serialize and Deserialize remote web service data or any data for that matter. Let’s see some code.
A simple example first. Below is the Datum struct.
struct Datum: Codable {
var name: String?
var detail: String?
}
Let’s see the encoding and decoding example of Datum.
func encodeDatum() {
// encode datum
do {
let datum = Datum(name: "data0", detail: "This is data0")
let jsonData = try JSONEncoder().encode(datum)
print(String(data: jsonData, encoding: .utf8)!)
} catch {
print("error: \(error)")
}
}
func decodeDatum() {
let jsonString = """
{
"name": "data0",
"detail": "This is data0"
}
"""
let jsonData = jsonString.data(using: .utf8)!
// decode datum
do {
let datum = try JSONDecoder().decode(Datum.self, from: jsonData)
print(datum)
} catch {
print("error: \(error)")
}
}
#swift #ios