Using Codable Protocol for Encoding and Decoding in Swift
📖 Scenario: You are building a simple app that stores information about books. You want to save this data to a file and also read it back later. Swift's Codable protocol helps you convert your data to and from a format that can be saved, like JSON.
🎯 Goal: Learn how to create a Swift struct that conforms to the Codable protocol, encode an instance to JSON data, decode JSON data back to the struct, and print the result.
📋 What You'll Learn
Create a struct called Book with properties title (String) and pages (Int)
Make Book conform to the Codable protocol
Create an instance of Book with title "Swift Programming" and pages 350
Encode the Book instance into JSON data
Decode the JSON data back into a Book instance
Print the decoded Book instance's title and pages
💡 Why This Matters
🌍 Real World
Apps often need to save user data or settings in a format like JSON. Codable makes it easy to convert Swift data to JSON and back.
💼 Career
Understanding Codable is essential for iOS developers to work with APIs, save data locally, and handle data serialization efficiently.
Progress0 / 4 steps
1
Create the Book struct conforming to Codable
Create a struct called Book with two properties: title of type String and pages of type Int. Make sure Book conforms to the Codable protocol.
Swift
Hint
Use struct Book: Codable and add the two properties inside.
2
Create a Book instance
Create a constant called myBook and assign it a Book instance with title set to "Swift Programming" and pages set to 350.
Swift
Hint
Use let myBook = Book(title: "Swift Programming", pages: 350).
3
Encode the Book instance to JSON data
Create a constant called jsonData and assign it the result of encoding myBook using JSONEncoder(). Use try? to handle errors.
Swift
Hint
Use JSONEncoder().encode(myBook) with try? to safely encode.
4
Decode JSON data and print the Book details
Decode jsonData back into a Book instance called decodedBook using JSONDecoder() and try?. Then print the title and pages of decodedBook separated by a comma and a space.
Swift
Hint
Use JSONDecoder().decode(Book.self, from: data) with try? and print the properties.
Practice
(1/5)
1. What is the main purpose of the Codable protocol in Swift?
easy
A. To create user interfaces quickly
B. To enable easy encoding and decoding of data to formats like JSON
C. To manage memory automatically
D. To handle network requests
Solution
Step 1: Understand Codable's role
The Codable protocol allows Swift types to be encoded to and decoded from external representations like JSON.
Step 2: Compare with other options
Options B, C, and D relate to UI, memory, and networking, which are unrelated to Codable.
Final Answer:
To enable easy encoding and decoding of data to formats like JSON -> Option B
Quick Check:
Codable = encoding/decoding data [OK]
Hint: Codable means convert data to/from JSON easily [OK]
Common Mistakes:
Confusing Codable with UI or networking protocols
Thinking Codable manages memory
Assuming Codable is for database operations
2. Which of the following is the correct way to declare a struct that supports encoding and decoding using Codable?
easy
A. struct User: Codable { var name: String; var age: Int }
B. struct User { var name: String; var age: Int }
C. struct User: Encodable { var name: String; var age: Int }
D. struct User: Decodable { var name: String; var age: Int }
Solution
Step 1: Check Codable conformance
To support both encoding and decoding, the struct must conform to Codable, which combines Encodable and Decodable.
Step 2: Analyze options
struct User: Codable { var name: String; var age: Int } correctly uses : Codable. Options C and D only support encoding or decoding, not both. struct User { var name: String; var age: Int } has no conformance.
Final Answer:
struct User: Codable { var name: String; var age: Int } -> Option A
Quick Check:
Use Codable to encode and decode both ways [OK]
Hint: Use Codable to encode and decode both ways [OK]
Common Mistakes:
Using only Encodable or Decodable when both needed
Forgetting to add Codable conformance
Declaring struct without protocol conformance
3. Given the following code, what will be printed?
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")
}
medium
A. Anna
B. Failed to decode
C. 30
D. nil
Solution
Step 1: Decode JSON string to Person
The JSON string matches the Person struct keys and types, so decoding succeeds.
Step 2: Print the name property
Since decoding succeeds, person.name is "Anna", which is printed.
Final Answer:
Anna -> Option A
Quick Check:
Decoded name = Anna [OK]
Hint: Match JSON keys exactly to struct properties [OK]
Common Mistakes:
Mismatching JSON keys and struct properties
Not unwrapping optional data safely
Confusing print output with age value
4. What is wrong with this code snippet that tries to decode JSON into a struct conforming to Codable?
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)
medium
A. The JSON string is not valid JSON
B. The struct does not conform to Codable
C. The JSON key "title" does not match the struct property "name"
D. The decoder is not initialized properly
Solution
Step 1: Compare JSON keys with struct properties
The JSON has key "title" but the struct expects "name"; this mismatch causes decoding to fail.
Step 2: Check other code parts
The struct conforms to Codable, JSON is valid, and decoder is correctly initialized, so no issues there.
Final Answer:
The JSON key "title" does not match the struct property "name" -> Option C
Quick Check:
JSON keys must match struct properties exactly [OK]
Hint: JSON keys must match struct property names exactly [OK]
Common Mistakes:
Ignoring key name mismatches
Assuming decoder setup causes error
Not validating JSON format
5. You want to encode a struct with an optional property that should be omitted from the JSON if it is nil. Which approach using Codable is correct?
hard
A. Declare the property as optional and use JSONEncoder's default behavior
B. Use Decodable instead of Codable
C. Make the property non-optional and assign a default value
D. Use a custom encode(to:) method to skip encoding nil properties
Solution
Step 1: Understand default Codable behavior
By default, JSONEncoder encodes optional properties as null if nil, not omitting them.
Step 2: Use custom encoding to omit nil
To omit nil optional properties, implement a custom encode(to:) method and encode only non-nil values.
Step 3: Evaluate other options
Declare the property as optional and use JSONEncoder's default behavior keeps nulls, C changes property type, B is unrelated to encoding.
Final Answer:
Use a custom encode(to:) method to skip encoding nil properties -> Option D
Quick Check:
Custom encode(to:) omits nil optionals [OK]
Hint: Custom encode(to:) skips nil optionals in JSON [OK]
Common Mistakes:
Expecting default encoder to omit nil optionals
Making optional properties non-optional unnecessarily
Confusing Decodable with encoding behavior
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.