0
0
Swiftprogramming~10 mins

Codable protocol for encoding/decoding in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Codable protocol for encoding/decoding
Define struct/class conforming to Codable
Create instance with data
Encode instance to JSON/Data
Transmit or save encoded data
Decode JSON/Data back to instance
Use decoded instance in code
This flow shows how a Swift type that conforms to Codable can be converted to and from JSON or other formats by encoding and decoding.
Execution Sample
Swift
struct User: Codable {
    var name: String
    var age: Int
}

let user = User(name: "Anna", age: 28)
let data = try JSONEncoder().encode(user)
let decodedUser = try JSONDecoder().decode(User.self, from: data)
This code creates a User, encodes it to JSON data, then decodes it back to a User instance.
Execution Table
StepActionEvaluationResult
1Create User instanceUser(name: "Anna", age: 28)User object with name=Anna, age=28
2Encode User to JSONJSONEncoder().encode(user){"name":"Anna","age":28} (Data)
3Decode JSON to UserJSONDecoder().decode(User.self, from: data)User(name: "Anna", age: 28)
4Use decoded UserAccess decodedUser.name and decodedUser.agename = "Anna", age = 28
5EndNo more stepsProcess complete
💡 Encoding and decoding complete, original and decoded User match
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
usernilUser(name: "Anna", age: 28)User(name: "Anna", age: 28)User(name: "Anna", age: 28)User(name: "Anna", age: 28)
datanilnil{"name":"Anna","age":28} (Data){"name":"Anna","age":28} (Data){"name":"Anna","age":28} (Data)
decodedUsernilnilnilUser(name: "Anna", age: 28)User(name: "Anna", age: 28)
Key Moments - 3 Insights
Why do we need to conform to Codable to encode/decode?
Conforming to Codable tells Swift how to convert the type to and from data formats like JSON. Without it, encoding or decoding will fail (see Step 2 and 3 in execution_table).
What happens if the JSON keys don't match the property names?
Decoding will fail or produce wrong results because Swift matches JSON keys to property names exactly. You can customize keys with CodingKeys, but here keys match (Step 3).
Is the decodedUser exactly the same as the original user?
Yes, after decoding, decodedUser has the same property values as user (Step 4), showing encoding and decoding preserved data.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'data' after Step 2?
AUser(name: "Anna", age: 28)
Bnil
C"{\"name\":\"Anna\",\"age\":28}" as Data
DJSONDecoder instance
💡 Hint
Check the 'data' variable value in variable_tracker after Step 2
At which step does decoding from JSON back to User happen?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for decoding
If the User struct did not conform to Codable, what would happen at Step 2?
AEncoding would fail with an error
BEncoding would succeed but decoding would fail
CDecoding would produce a default User
DNothing would change
💡 Hint
Refer to key_moments about the importance of Codable conformance
Concept Snapshot
Codable protocol allows Swift types to be encoded to and decoded from formats like JSON.
Conform your struct/class to Codable.
Use JSONEncoder to encode an instance to Data.
Use JSONDecoder to decode Data back to an instance.
Property names must match JSON keys or use CodingKeys.
Encoding and decoding preserve data structure.
Full Transcript
This visual trace shows how a Swift struct named User, which conforms to Codable, is created with properties name and age. The User instance is then encoded into JSON data using JSONEncoder. This JSON data is a serialized form representing the User's properties. Next, JSONDecoder decodes this data back into a User instance. The decoded instance has the same property values as the original, demonstrating that encoding and decoding preserve the data. Variables user, data, and decodedUser change values step-by-step as shown. Key points include the need for Codable conformance to enable encoding and decoding, the importance of matching property names to JSON keys, and confirmation that the decoded object matches the original. The quiz questions test understanding of these steps and the role of Codable.