Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
40: Working with JSON in Swift
At some point in your career, you're going to have to pull data from a web API. Almost every modern API speaks JSON, and if you've spent any time in JavaScript or Python, you're probably used to just treating JSON as a giant, flexible dictionary. When you first move into Swift, it's tempting to bring that same mindset with you. I've seen plenty of developers try to "brute force" their way through JSON parsing because they didn't want to spend time defining models for data they thought was simple.
The fragility of casting everything
The "naive" way to handle JSON in Swift is using JSONSerialization. This approach basically turns your JSON string into a Any type—usually a [String: Any] dictionary—and then leaves you to figure out what's inside. Let's say we're building a weather app and the API gives us a response like this: {"city": "Seattle", "temp": 55, "conditions": "Rainy"}.
let jsonData = jsonString.data(using: .utf8)!
if let dictionary = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
if let city = dictionary["city"] as? String {
print("The weather in \(city) is...")
}
if let temp = dictionary["temp"] as? Int {
print("It is \(temp) degrees.")
}
}
On the surface, this looks fine. But as a professional, this makes me nervous. Why? Because you're relying on "stringly-typed" code. If the API provider changes "city" to "cityName", your code doesn't crash, but the if let fails silently and your UI just stays empty. Even worse, you're casting types manually everywhere. If the API suddenly starts sending the temperature as a double (55.5) instead of an integer, your as? Int cast fails, and your app "breaks" even though the data is technically still there. It's a maintenance nightmare that scales poorly the moment your JSON gets nested.
Letting the compiler do the heavy lifting
The better way—and the way you should be doing this in any production app—is using the Codable protocol. Instead of treating the JSON as a bag of mystery values, we define a blueprint of what we expect. By creating a struct that conforms to Decodable, we tell Swift exactly how the data should look. If the data doesn't match the blueprint, the decoder throws a clear error telling us exactly which key was missing or which type was mismatched.
struct WeatherResponse: Codable {
let city: String
let temp: Int
let conditions: String
}
let decoder = JSONDecoder()
do {
let weather = try decoder.decode(WeatherResponse.self, from: jsonData)
print("The weather in \(weather.city) is \(weather.temp) degrees.")
} catch {
print("Decoding failed: \(error)")
}
Now, we have type safety. We aren't guessing if temp is an Int; the compiler guarantees it. If the API changes and city disappears, the catch block triggers immediately, letting us know exactly what went wrong during development rather than hunting for a silent bug in production.
Bridging the gap between API style and Swift style
Here is where things usually get tricky: APIs rarely follow Swift's camelCase naming conventions. You'll often encounter snake_case keys like current_temperature. You could name your Swift properties current_temperature to match, but that feels wrong in a Swift codebase. I hate seeing snake_case in my structs; it just looks out of place.
You have two choices here. The "quick" way is to tell the JSONDecoder to convert snake_case automatically using .convertFromSnakeCase. But if the API names are truly erratic (like Temp_Val_2023), that won't help. In those cases, we use CodingKeys. This is a special enum inside your struct that maps the JSON key name to your preferred Swift property name.
struct WeatherResponse: Codable {
let city: String
let temperature: Int
enum CodingKeys: String, CodingKey {
case city
case temperature = "temp_val"
}
}
This approach gives you the best of both worlds. You keep your Swift code clean and idiomatic, while still being able to consume data from a backend that might have been written in a completely different language or era. It moves the "translation" logic into a single, declarative place rather than scattering as? casts throughout your view controllers.
📋 Practical Task
Exercise: Building a Movie Metadata Parser
You've been given a JSON response from a movie database API. Your task is to create a type-safe way to parse this data. The API returns the following JSON string:
"{"movie_title": "Inception", "release_year": 2010, "director": {"name": "Christopher Nolan", "nationality": "British"}}"
Requirements:
- Create a
Directorstruct and aMoviestruct that conform toCodable. - Use
CodingKeysto mapmovie_titleto a Swift property namedtitleandrelease_yeartoyear. - The
Directorstruct should be nested inside theMoviestruct. - Write the code to decode a JSON string into your
Moviestruct usingJSONDecoder. - Print the director's name and the movie title to the console to verify it works.
There are no comments for now.