Using UserDefaults correctly

Persistence Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

Which of these belongs in UserDefaults?

Options
Hint 1 of 1

Small, non-sensitive and a preference.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A The user's preferred theme

Correct. It's small, non-sensitive and a preference.

Why not the others?
  • B The access token. Tokens belong in the Keychain; UserDefaults is unencrypted.
  • C A 5 MB message cache. Large data slows launch, because the whole plist loads into memory.
  • D The user's profile photo. Images belong in files or a cache.

30-second answer

Use UserDefaults for small, non-sensitive preferences such as a theme, a sort order or an onboarding flag. Wrap keys in one place (or @AppStorage in SwiftUI) to avoid typos, register defaults at launch, and use an App Group suite to share with extensions. Never store tokens or passwords there; the plist is unencrypted.

Practise saying it · 30 s. No recording, just a timer

Explain how you use UserDefaults.

Say your answer out loud, then check which of these points you covered:

  • Small preferences only
  • Centralised keys
  • No secrets

Deep dive

register(defaults:) sets fallback values without writing them.

synchronize() is not needed.

Codable values can be stored as Data, but keep them small.

Using UserDefaults is a required-reason API in the privacy manifest.

Common mistakes

  • Storing secrets.
  • Storing large arrays or images.

Senior take & follow-ups

Seniors keep keys typed and centralised, and mention privacy manifests.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why is synchronize unnecessary?

    Show hint

    The system persists changes automatically.

  2. What must the privacy manifest declare?

    Show hint

    The reason for using UserDefaults APIs.

Suggest a fix if something here is wrong or out of date.