The Codable protocol helps your app easily convert data between Swift objects and JSON format. This makes reading and saving data simple and safe.
When you want to load data from a web service that sends JSON.
When you need to save app data as JSON files on the device.
When you want to send data from your app to a server in JSON format.
When you want to convert JSON data into Swift objects to use in your app.
When you want to convert Swift objects into JSON to share or store.
Syntax
iOS Swift
struct MyData: Codable {
var name: String
var age: Int
}
Use Codable on structs or classes to make them able to convert to/from JSON.
Properties must be standard types like String, Int, Double, Bool, or other Codable types.
Examples
A simple user struct that can be encoded to or decoded from JSON.
iOS Swift
struct User: Codable {
var username: String
var score: Int
}
This struct can represent a product and be converted to JSON easily.
iOS Swift
struct Product: Codable {
var id: Int
var name: String
var price: Double
}
Optional properties like message can be nil if JSON does not include them.
iOS Swift
struct Response: Codable {
var success: Bool
var message: String?
}
Sample App
This example shows how to decode a JSON string into a Person object using Codable. It prints the person's name and age.
iOS Swift
import Foundation
struct Person: Codable {
var name: String
var age: Int
}
let jsonString = "{\"name\": \"Alice\", \"age\": 30}"if let jsonData = jsonString.data(using: .utf8) {
let decoder = JSONDecoder()
if let person = try? decoder.decode(Person.self, from: jsonData) {
print("Name: \(person.name), Age: \(person.age)")
} else {
print("Failed to decode JSON")
}
}
OutputSuccess
Important Notes
Always handle decoding errors safely using try? or do-catch.
Use JSONEncoder to convert Swift objects back to JSON data.
Codable works best with simple data types and nested Codable structs.
Summary
Codable makes converting between Swift objects and JSON easy.
Use JSONDecoder to read JSON into Swift objects.
Use JSONEncoder to write Swift objects as JSON.
Practice
(1/5)
1. What does the Codable protocol in Swift help you do?
easy
A. Convert Swift objects to and from JSON easily
B. Create user interface elements
C. Manage app navigation
D. Handle network connections
Solution
Step 1: Understand the purpose of Codable
The Codable protocol is designed to simplify converting data between Swift objects and external formats like JSON.
Step 2: Identify the correct use case
It is not related to UI, navigation, or networking directly, but specifically for encoding and decoding data.
Final Answer:
Convert Swift objects to and from JSON easily -> Option A
Quick Check:
Codable = Convert JSON [OK]
Hint: Codable means easy JSON conversion [OK]
Common Mistakes:
Confusing Codable with UI or navigation tasks
Thinking Codable manages network calls
Assuming Codable is for database storage
2. Which of the following is the correct way to declare a Swift struct that can be encoded and decoded using Codable?
easy
A. struct User { var name: String }
B. struct User: Decodable { var name: String }
C. class User: Codable { var name: String }
D. struct User: Codable { var name: String }
Solution
Step 1: Check the struct declaration
To use Codable, the struct must conform to the Codable protocol explicitly.
Step 2: Verify the syntax
struct User: Codable { var name: String } correctly declares a struct conforming to Codable. struct User { var name: String } lacks Codable conformance. class User: Codable { var name: String } uses a class, which is valid but not asked here. struct User: Decodable { var name: String } only conforms to Decodable, missing Encodable.
Final Answer:
struct User: Codable { var name: String } -> Option D