Saving Data: UserDefaults, Keychain and Files
Where to Store What
| Data | Best place |
|---|---|
| Small settings and flags | UserDefaults / @AppStorage |
| Passwords, tokens, secrets | Keychain |
| A document or small JSON file | File in the Documents folder |
| Lists of structured objects, queries | SwiftData (next lesson) |
| Photos and videos | Photo library or files |
UserDefaults
swift
let defaults = UserDefaults.standard
defaults.set("Asha", forKey: "name")
defaults.set(true, forKey: "darkMode")
let name = defaults.string(forKey: "name") ?? "Guest"
let dark = defaults.bool(forKey: "darkMode")
defaults.removeObject(forKey: "name")
Keychain
The Keychain is an encrypted store managed by iOS. It is the right place for tokens and passwords.
swift
import Security
enum Keychain {
static func save(_ value: String, for key: String) {
let data = Data(value.utf8)
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key
]
SecItemDelete(query as CFDictionary) // remove the old value
var add = query
add[kSecValueData as String] = data
add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
SecItemAdd(add as CFDictionary, nil)
}
static func read(_ key: String) -> String? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne
]
var result: AnyObject?
guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
let data = result as? Data else { return nil }
return String(data: data, encoding: .utf8)
}
static func delete(_ key: String) {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key
]
SecItemDelete(query as CFDictionary)
}
}
Keychain.save("abc123token", for: "authToken")
print(Keychain.read("authToken") ?? "none")
Why not UserDefaults? UserDefaults data is stored in a plain file that can be read from a backup. The Keychain is encrypted and stays protected.
Saving a File
swift
struct Note: Codable, Identifiable {
var id = UUID()
var text: String
}
enum NoteStore {
private static var fileURL: URL {
URL.documentsDirectory.appending(path: "notes.json")
}
static func save(_ notes: [Note]) throws {
let data = try JSONEncoder().encode(notes)
try data.write(to: fileURL, options: [.atomic, .completeFileProtection])
}
static func load() -> [Note] {
guard let data = try? Data(contentsOf: fileURL) else { return [] }
return (try? JSONDecoder().decode([Note].self, from: data)) ?? []
}
}
Use It in a View
swift
struct NotesView: View {
@State private var notes = NoteStore.load()
@State private var text = ""
var body: some View {
NavigationStack {
List {
HStack {
TextField("New note", text: $text)
Button("Add") {
notes.append(Note(text: text))
text = ""
}
}
ForEach(notes) { Text($0.text) }
.onDelete { notes.remove(atOffsets: $0) }
}
.navigationTitle("Notes")
.onChange(of: notes.count) { try? NoteStore.save(notes) }
}
}
}
Folders in Your App
| Folder | Use |
|---|---|
documentsDirectory | User-created files, backed up |
cachesDirectory | Re-creatable data, system may delete it |
temporaryDirectory | Short-lived files |
Tip: Files are good for simple data. When you need search, sorting, relationships or lots of records, move to SwiftData.
Conclusion
Pick the right container: UserDefaults for tiny settings, Keychain for secrets and files or SwiftData for real content.
Quick Summary: UserDefaults for settings, Keychain for secrets, Codable JSON files for simple documents and SwiftData for larger data.

