tezvyn:

How do you persist a custom Swift struct to JSON in Documents?

AI-drafted, machine-checkedSource: developer.apple.combeginner
How do you persist a custom Swift struct to JSON in Documents?

Tests fluency with Codable and FileManager sandbox APIs. Good answer: conform to Codable, encode with JSONEncoder, resolve Documents directory via FileManager URLs, write Data atomically, and reverse with JSONDecoder.

WHAT THIS TESTS: This question probes whether you know the platform-idiomatic way to serialize custom types in Swift. The interviewer wants to hear Codable as the default contract between your model and JSON, paired with FileManager for sandbox-aware file URLs. For a senior candidate, it is also a check against unnecessary complexity like third-party serialization libraries or manual Dictionary mapping when the standard library already solves the problem.

A GOOD ANSWER COVERS: First, declare that the struct conforms to Codable, which gives you automatic synthesized encoding and decoding as long as every stored property is also Codable. Second, describe the write path: instantiate JSONEncoder, call encode on your struct to produce Data, then locate the Documents directory by calling FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) and appending your filename. Third, write that Data to disk using write(to:options:), mentioning that you can pass .atomic for safe writes. Fourth, describe the read path: initialize Data with contentsOf the file URL, then use JSONDecoder to decode back into your struct type. Fifth, mention error handling with do-catch or Result, because any of these steps can throw.

COMMON WRONG ANSWERS: Using NSSearchPathForDirectoriesInDomains instead of the URL-based FileManager API is an older pattern that signals stale knowledge. Building JSON by hand with string interpolation or Dictionary serialization is a red flag for ignoring Codable. Force-trying every step with try! or silently discarding errors with try? without discussion shows a lack of production awareness. Attempting to write into the main bundle instead of Documents or Library indicates misunderstanding of the iOS sandbox. Finally, forgetting that Codable synthesis requires all nested types to also conform to Codable will cause a compile-time failure that a candidate should be able to explain.

LIKELY FOLLOW-UPS: The interviewer may ask how you would handle schema changes or versioning if you add a new property to the struct later. They might also ask about custom encoding keys if the JSON keys should differ from the property names. Another angle is performance: how large can this file get before you should switch to Core Data or SQLite? They could also ask about concurrency, such as whether you perform these operations on a background queue to avoid blocking the main thread.

ONE CONCRETE EXAMPLE: Imagine a struct named UserSettings with two properties, var theme: String and var notificationsEnabled: Bool. To persist it, you create let encoder = JSONEncoder(), then let data = try encoder.encode(userSettings). You resolve the file URL with let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!, then let fileURL = documentsDirectory.appendingPathComponent("settings.json"). Finally, you call try data.write(to: fileURL, options: .atomic). To read it back, you use let data = try Data(contentsOf: fileURL) and let decoded = try JSONDecoder().decode(UserSettings.self, from: data).

Source: developer.apple.com

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.