← All courses

Data Persistence

🗓 May 31, 2026 ⏱ 1 min read

UserDefaults (small settings)

UserDefaults.standard.set(true, forKey: "darkMode")
let dark = UserDefaults.standard.bool(forKey: "darkMode")

Saving Codable objects to a file

let data = try JSONEncoder().encode(users)
let url = FileManager.default
    .urls(for: .documentDirectory, in: .userDomainMask)[0]
    .appendingPathComponent("users.json")
try data.write(to: url)

Core Data (full database)

Core Data is Apple’s framework for large, related, persistent data. You model entities in a visual editor, then fetch and save through a managed object context. For new apps, SwiftData (iOS 17+) offers a simpler, Swift-first API over the same engine.

Choose by need: a few flags → UserDefaults; structured documents → Codable + files; large relational data → Core Data / SwiftData.