0
0
iOS Swiftmobile~5 mins

UserDefaults for simple values in iOS Swift

Choose your learning style9 modes available
Introduction

UserDefaults lets your app save small pieces of information like settings or preferences. This way, the app remembers them even after you close it.

Saving a user's preferred app theme (light or dark).
Remembering if the user has seen a welcome message.
Storing a simple counter like how many times the app was opened.
Saving a user's name to greet them next time.
Keeping track of a toggle switch state in settings.
Syntax
iOS Swift
let defaults = UserDefaults.standard

// Save a value
defaults.set(value, forKey: "key")

// Read a value
let value = defaults.value(forKey: "key")

Use set(_:forKey:) to save values like strings, numbers, or booleans.

Use value(forKey:) or typed methods like string(forKey:) to read values.

Examples
Saves a boolean and reads it back.
iOS Swift
let defaults = UserDefaults.standard
defaults.set(true, forKey: "hasSeenWelcome")
let seen = defaults.bool(forKey: "hasSeenWelcome")
Saves a string and reads it back.
iOS Swift
let defaults = UserDefaults.standard
defaults.set("John", forKey: "username")
let name = defaults.string(forKey: "username")
Saves an integer and reads it back.
iOS Swift
let defaults = UserDefaults.standard
defaults.set(42, forKey: "launchCount")
let count = defaults.integer(forKey: "launchCount")
Sample App

This app shows a welcome message. The first time you open it, it shows "Welcome for the first time!" with a button. When you tap the button, it saves that you have seen the welcome. Next time you open the app, it shows "Welcome back!" because it reads the saved value.

iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var hasSeenWelcome = UserDefaults.standard.bool(forKey: "hasSeenWelcome")

    var body: some View {
        VStack(spacing: 20) {
            if hasSeenWelcome {
                Text("Welcome back!")
            } else {
                Text("Welcome for the first time!")
                Button("Got it") {
                    hasSeenWelcome = true
                    UserDefaults.standard.set(true, forKey: "hasSeenWelcome")
                }
            }
        }
        .padding()
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
OutputSuccess
Important Notes

UserDefaults is good for small, simple data only. Don't use it for big files or sensitive info.

Always use the same key string to save and read the value.

Changes to UserDefaults are saved immediately, so no extra saving step is needed.

Summary

UserDefaults stores small pieces of data that your app can remember between launches.

Use set(_:forKey:) to save and typed methods like bool(forKey:) to read.

Good for simple settings like toggles, counters, or user names.