UserDefaults example in Swift

UserDefaults is a simple way to store small amounts of data persistently across app launches. It’s ideal for storing user preferences or other small pieces of data. However, it’s not suitable for storing large amounts of data, as it can slow down your app’s startup time.

This is going to be a short tutorial with a very simple code example, but it will contain a lot of useful details like:

  • Create a global instance of UserDefaults.
  • Writing data to UserDefaults.
  • Reading data from UserDefaults.
  • Removing data from UserDefaults.
  • Create a simple iOS app to demonstrate UserDefaults.

Step 1: Create a Global Instance of UserDefaults

To start using UserDefaults, you first need to create a global instance. This is usually done at the beginning of your program. Here’s how you can do it:

let defaults = UserDefaults.standard

This creates a new instance of UserDefaults, which is a standard way to interact with the UserDefaults system.

Step 2: Writing Data to UserDefaults

You can write different types of data to UserDefaults using the set function. This function takes two parameters:

  1. The value you want to store, and
  2. A unique key to identify the value. Here’s how you can store an integer, a boolean, and a double:
defaults.set(25, forKey: "Age") // Integer
defaults.set(true, forKey: "UseTouchID")// Boolean
defaults.set(CGFloat.pi, forKey: "Pi") // Double

You can also store more complex types like strings, dates, and arrays:

defaults.set("John Doe", forKey: "UserName") // String
defaults.set(Date(), forKey: "LastLogin") // Date
defaults.set([1, 2, 3], forKey: "Scores") // Array

Remember to choose keys that are unique and descriptive, as they will be used to retrieve the data later.

Step 3: Reading Data from UserDefaults

To read data from UserDefaults, you use the object(forKey:) function, passing in the key you used to store the data. This function returns an optional value, which means it can either contain the stored value or nil if no value was found for the given key. Here’s how you can read the data we stored earlier:

if let age = defaults.object(forKey: "Age") as? Int {
   print("Age: \(age)")
}

if let useTouchID = defaults.object(forKey: "UseTouchID") as? Bool {
   print("Use Touch ID: \(useTouchID)")
}

if let pi = defaults.object(forKey: "Pi") as? Double {
   print("Pi: \(pi)")
}

Again, remember to cast the returned value to the correct type.

Step 4: Removing Data from UserDefaults

If you want to delete data from UserDefaults, you can use the removeObject(forKey:) function:

defaults.removeObject(forKey: "Age")

This removes the data associated with the key “Age”. Be careful with this operation, as it cannot be recovered once data is deleted.

Create a simple iOS app to demonstrate UserDefaults

Let’s create a simple iOS app that demonstrates the above discussion using Swift. I hope it makes your understanding more clear.

struct UserDefaultsView: View {
    @State private var name: String = ""
    
    let defaults = UserDefaults.standard

    var body: some View {
        VStack {
            TextField("Enter your name", text: $name)
                .padding()
                .border(Color.gray, width: 0.5)
            
            Button("Save") {
                defaults.set(name, forKey: "Name")
                print("Userdefaults created for key Name")
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)
            
            Button("Delete") {
                defaults.removeObject(forKey: "Name")
                name = ""
                print("Userdefaults deleted for key Name")
            }
            .padding()
            .background(Color.red)
            .foregroundColor(.white)
            .cornerRadius(10)
            
            if !name.isEmpty {
                Text("Hello, \(name)!")
                    .font(.largeTitle)
            }
        }
        .padding()
    }
}

In the above code example, I first create an instance of UserDefaults using let defaults = UserDefaults.standard. Then, I created two different buttons for saving and deleting the user defaults. When the “Save” button is pressed, the value of the name variable is saved to UserDefaults with the key “Name” using defaults.set(name, forKey: "Name"). When the “Delete” button is pressed, the value associated with the key “Name” is removed from UserDefaults using defaults.removeObject(forKey: "Name").

NSUserDefaults example in Swift

In the screenshot above, a demonstration shows the process of saving a name to UserDefaults and subsequently deleting it. However, upon restarting or closing the app, the saved information persists and does not get erased automatically. It remains stored in UserDefaults until manually deleted.

Conclusion

I hope this tutorial was helpful to you.

UserDefaults is a powerful tool for storing small amounts of data persistently. However, it’s not designed for storing large amounts of data. For larger data sets, consider using other data persistence techniques, such as Core Data, Swift Data, or SQLite.

For more Swift Code examples and tutorials, please check the Swift Code Examples page on this website.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *