🥷🏻 Parsing JSON using the Codable Protocol 📋
Need to capture HTTPS traffic?
Try Proxyman ❤️ the best-in-class macOS app, and capture HTTPS traffic from the iOS, Simulator with 1 click. Used by 250,000+ developers. Try it for free now!
Welcome to issue #37 of the iOS Coffee Break Newsletter 📬
If you have been following the newsletter, you should know that I have decided to build an app for it and document the process! I am glad to welcome you to the 1st issue of the "Building a Newsletter App" series!
Based on last week's survey, I now have a better understanding of what topics interest my readers the most. To kick things off, I will start with a beginner-friendly topic: parsing JSON using the Codable protocol.
As the app evolves and becomes more complex, I will introduce more advanced topics!
Hope you enjoy ✌️!
🧐 Sneak Peek: Issues View
Here is a glimpse of what I am aiming for with the issues view — a straightforward list displaying all past newsletter issues in a clean and accessible way.
The Plan
Here are the steps I need to perform to get this done:
- Define the Issue struct and ensure it conforms to the Codable protocol.
- Retrieve issue data from the newsletter API feed.
- Decode the fetched data into an array of Issue objects.
- Use the decoded data to populate the view.
The Codable Protocol
The Codable protocol in Swift simplifies data conversion between Swift types and formats like JSON or XML. It merges two protocols: Encodable (for encoding Swift objects) and Decodable (for decoding external data).
By making Issue
conform to Codable, we can seamlessly encode and decode instances to and from JSON, making it easy to fetch and store data in a structured format.
struct Issue: Hashable, Codable, Identifiable {
let id: String
let content: String
let url: String
let title: String
let summary: String
let date: Date
let author: Author
let tags: [String]
}
The only requirement of declaring a Codable is that all of its stored properties must also be Codable.
Mapping JSON Keys with CodingKeys
Sometimes, JSON keys don't match your Swift property names. The CodingKeys enum helps map them correctly.
struct Issue: Hashable, Codable, Identifiable {
[...]
enum CodingKeys: String, CodingKey {
case id, url, title, summary, author, tags
case content = "content_html"
case date = "date_modified"
}
}
If a required field is missing in the JSON, decoding will fail unless you handle it properly by providing default values or making the property optional.
Here, the content
property corresponds to content_html
in the JSON, and date
corresponds to date_modified
.
Decoding from JSON
By making custom types like Issue
and Author
conform to Codable, we enable encoding and decoding between Swift objects and data formats like JSON.
In this case, JSONDecoder is used to transform a JSON string into its equivalent model type in Swift.
class APIClient {
[...]
func getIssues() async -> [Issue] {
guard let url = URL(string: "https://www.ioscoffeebreak.com/api/feed.json") else { return [] }
let request = URLRequest(url: url)
do {
let (data, _) = try await session.data(for: request)
let issuesResponse = try decoder.decode(IssuesResponse.self, from: data)
return issuesResponse.issues
} catch {
print("Error fetching issues: \(error)")
return []
}
}
}
Wrapping Up
And with that, we have covered how to conform to the Codable protocol, define CodingKeys, and implement custom decoding methods.
By understanding these concepts, you can efficiently work with your data models, ensuring consistent encoding and decoding for external formats like JSON.
CURATED FROM THE COMMUNITY
💪 The Power of Consistency: a Path to Indie Development - Pol Piella
Antoine's latest episode of the Going Indie Podcast features Pol Piella, an iOS dev and content creator I have been following for a while — especially when I need insights on CI/CD topics!
As soon as it was announced, I knew I had to highlight it in the newsletter. Pol's journey has been a huge inspiration for me in building a public profile and starting to create and share content — big kudos to him 👏!
✂️ How to remove unwanted Swift Package schemes in Xcode
I bet you have been annoyed by random package schemes being listed in your Xcode project!
In his latest article, Jesse shares a solution to clean up those unwanted Swift package schemes in Xcode. He even provides a handy script that you can integrate into your build process or run manually whenever needed!
🤝 Git Hooks in Swift
Swift as a Git Hook? Did I read that right?
In his latest post on Swift Toolkit, Natan walks through setting up Git hooks in a project. He starts with a basic bash script and then demonstrates how to implement them in Swift — both as a script and as a compiled executable.
🥶 ARCtic iOS conference 2025
If ARCtic Conference was high on your list this year but you couldn't make it, here are some good news!
Daniel has put together a special page on his blog where he shares detailed notes from each talk. It is unclear if the sessions will be publicly available, but in the meantime, you can check out his insights from the talks he enjoyed the most!