SwiftData uses SQLite as its underlying storage engine, and sometimes we may need to delete the database, typically during development or testing.

However, if the application is in production then we should be working with migrations instead of deleting the database.

Here’s how to delete the database safely.

Locating the SQLite Database

First, we need to locate the SQLite database file. The database file is typically stored in our app’s sandboxed documents directory. We can find its location by printing the URL in our code:

if let container = try? ModelContainer(for: YourModel.self) {
    print(container.configurations.first?.url ?? "No URL found")
}

This will output a path similar to:

/Users/william/Library/Containers/uk.co.domainname.appname/Data/Library/Application Support/default.store

We can also find the database file in the Xcode Organizer under the “Devices and Simulators” section, where we can download the app’s container.

Deleting the Database

To delete the SwiftData database, we can use the following code snippet:

if let container = try? ModelContainer(for: YourModel.self) {
    do {
        try container.deleteStore()
        print("Database deleted successfully.")
    } catch {
        print("Failed to delete database: \(error)")
    }
}

This code attempts to delete the database associated with our SwiftData model. If successful, it will print a confirmation message; otherwise, it will print an error message.