Introduction
The Codable protocol helps you easily convert your Swift data into formats like JSON and back. This makes saving and sharing data simple.
The Codable protocol helps you easily convert your Swift data into formats like JSON and back. This makes saving and sharing data simple.
struct MyData: Codable { var name: String var age: Int }
struct Person: Codable { var firstName: String var lastName: String var age: Int }
let jsonData = try JSONEncoder().encode(person) let personAgain = try JSONDecoder().decode(Person.self, from: jsonData)
class Book: Codable { var title: String var pages: Int init(title: String, pages: Int) { self.title = title self.pages = pages } }
This program creates a User, converts it to JSON text, prints it, then converts the JSON back to a User and prints the details.
import Foundation struct User: Codable { var username: String var score: Int } let user = User(username: "alice", score: 42) // Encode user to JSON if let jsonData = try? JSONEncoder().encode(user) { print("JSON String:") if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) } // Decode JSON back to User if let decodedUser = try? JSONDecoder().decode(User.self, from: jsonData) { print("Decoded User:") print("Username: \(decodedUser.username), Score: \(decodedUser.score)") } }
Make sure all properties in your type are also Codable.
If you want to customize encoding or decoding, you can implement init(from:) and encode(to:) methods.
Codable makes converting Swift data to and from formats like JSON easy.
Use Codable on your structs or classes to enable this automatic conversion.
Encoding turns your data into JSON; decoding turns JSON back into your data.
Codable protocol in Swift?Codable protocol allows Swift types to be encoded to and decoded from external representations like JSON.Codable.Codable, which combines Encodable and Decodable.: Codable. Options C and D only support encoding or decoding, not both. struct User { var name: String; var age: Int } has no conformance.struct Person: Codable {
var name: String
var age: Int
}
let jsonData = "{\"name\": \"Anna\", \"age\": 30}".data(using: .utf8)!
let decoder = JSONDecoder()
if let person = try? decoder.decode(Person.self, from: jsonData) {
print(person.name)
} else {
print("Failed to decode")
}person.name is "Anna", which is printed.struct Product: Codable {
var id: Int
var name: String
}
let json = "{\"id\": 101, \"title\": \"Book\"}"
let data = json.data(using: .utf8)!
let decoder = JSONDecoder()
let product = try? decoder.decode(Product.self, from: data)encode(to:) method and encode only non-nil values.Pass the test and this pattern moves unknown