0
0
Swiftprogramming~30 mins

Codable protocol for encoding/decoding in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use JSONDecoder().decode(Book.self, from: data) with try? and print the properties.