How to Save Local Data in a Swift App
In this article
To save local data in a Swift app, use Apple's built-in persistence frameworks: UserDefaults for small preferences, the file system for larger files, and Core Data or SwiftData for structured objects. All three work offline and require no third-party library. The right choice depends on what you are storing and how much of it there is.
What You'll Need
- Xcode installed on a Mac, with a SwiftUI or UIKit project open.
- A basic understanding of Swift types such as
String,Int, andCodablestructs. - An iOS, iPadOS, or macOS target (the same APIs work on all Apple platforms, though menu labels and file locations can differ slightly by version and device).
Step-by-Step
- Decide what kind of data you are saving. Use UserDefaults for small values like a username, a toggle state, or a high score. Use files for images, JSON exports, or anything larger than a few kilobytes. Use Core Data or SwiftData when you need to query, sort, or relate many records. Mixing these up is the most common cause of slow apps and lost data.
- Save a simple value with UserDefaults. Call
UserDefaults.standard.set(value, forKey: "myKey")wherevalueis aString,Int,Bool,Double, orData. Read it back withUserDefaults.standard.string(forKey: "myKey")or the matching typed getter. UserDefaults writes to disk automatically, so you do not need a save call. - Store a custom struct as Codable data. Make your struct conform to
Codable, encode it withJSONEncoder().encode(myStruct), and save the resultingDatain UserDefaults. Decode it withJSONDecoder().decode(MyStruct.self, from: data). This keeps small objects tidy without a database. - Write larger data to a file. Get a directory with
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!, append a filename, and write withtry data.write(to: url, options: .atomic). The.atomicoption prevents a half-written file if the app crashes mid-save. Read it back withtry Data(contentsOf: url). - Use SwiftData for structured records. In a SwiftUI app, add a model with the
@Modelmacro, attach aModelContainerto your view hierarchy, and insert objects through the model context. SwiftData handles saving, fetching, and relationships. Core Data remains the older alternative and uses the same underlying store; pick one and stay consistent. - Handle errors instead of ignoring them. Wrap file writes and decodes in
do/catchand log the error. A silent failure here is why data appears to vanish between launches. - Test persistence across launches. Run the app, save a value, stop it in Xcode, and run again. If the value is missing, check that you are reading the same key or file path and that the write actually executed.
Common Mistakes
- Using UserDefaults for large data. It loads into memory at launch; storing images or long lists there slows startup and is not what it is designed for.
- Forgetting the atomic write option. A crash during a plain write can leave a corrupt file that fails to decode on the next launch.
- Hardcoding file paths. The app's container path changes between installs and devices. Always build paths from
FileManagerURLs. - Ignoring thread safety. Core Data and SwiftData contexts are not safe to share across threads without the proper context setup. Keep UI work on the main context.
- Assuming data survives app deletion. Removing the app deletes its container, including files and databases. UserDefaults is also cleared. Only iCloud or an external backup preserves it.
Tips
- Keep keys in one constants file so a typo in a string does not silently create a second, empty entry.
- Version your saved JSON with a schema field so future changes can migrate old data instead of crashing on decode.
- Use
FileManager's application support directory for app-managed data and the documents directory only for files the user should see. - For sensitive values like tokens, use the Keychain instead of UserDefaults; UserDefaults is not encrypted.
- Write a small unit test that saves, reloads, and compares the value. It catches most persistence regressions early.
Troubleshooting
If saved data is missing after relaunch, first confirm the write ran by adding a print or breakpoint right after the save call. Then check that the read uses the identical key or filename. If you changed the struct's properties, old JSON may no longer decode; add default values or a migration step. If file writes fail, verify you are writing inside the app's container and not to a read-only location. If Core Data or SwiftData fetches return nothing, confirm the model container was attached before the view that queries it. As a last resort, delete the app from the simulator or device and reinstall to clear a corrupted store, but note this erases all locally saved data.
Frequently Asked Questions
Is UserDefaults safe for passwords?
No. It is stored unencrypted. Use the Keychain for passwords and tokens.
Does local data sync between devices?
Not by default. Local storage stays on one device unless you add iCloud or another sync layer.
Can I use these APIs on macOS and watchOS?
Yes. UserDefaults, FileManager, Core Data, and SwiftData are available across Apple platforms, with some API differences on watchOS.
What happens to saved data when the app is updated?
It is preserved. Updating an app keeps its container; only deleting the app removes local data.
Should I use Core Data or SwiftData?
SwiftData is the newer, simpler option for new SwiftUI projects. Core Data is still valid for existing apps and older deployment targets.