Keep Registered Defaults From Leaking Between Swift Tests

Two tests create two uniquely named UserDefaults suites. One registers a setting as true; the other registers the same setting as false. Neither saves a value. Surely they cannot affect each other.

They can. Unique suites isolate their saved values, but their registered fallbacks are shared within the process. A UUID is a useful address. It is not a process boundary.

This matters when moving tests to Swift Testing, where tests and parameterized cases run concurrently by default. Let’s reproduce the behavior, then give each test ownership of both its saved domain and its registered keys.

A separate suite still has shared fallbacks

Apple’s init(suiteName:) documentation explicitly says that defaults instances share the argument and registration domains. Calling register(defaults:) on a custom instance does not create a registration domain just for that instance.

Jeff Johnson described a real migration bug caused by this behavior, which also prompted discussion on Michael Tsai’s blog. Here we’ll apply that observation to test isolation. The behavior is documented; the surprising part is its scope.

First, give the reproduction temporary storage. Put the following blocks together in a Swift Testing test target using Swift 6.2 or later. The explicit nonisolated declarations also let these non-UI tests run independently in projects that default to MainActor isolation; they don’t provide storage isolation.

This fixture creates one suite per instance and can derive keys unique to that instance:

import Foundation
import Testing

nonisolated struct DefaultsFixture {
    let suiteName = "com.theswiftdev.preference-tests.\(UUID().uuidString)"
    let defaults: UserDefaults

    init() throws {
        defaults = try #require(UserDefaults(suiteName: suiteName))
    }

    func key(_ name: String) -> String {
        "\(suiteName).\(name)"
    }

    func cleanUp() {
        defaults.removePersistentDomain(forName: suiteName)
    }
}

For this first test, deliberately use one shared key in two different suites. The test passes by checking the surprising result:

@Test
nonisolated func separateSuitesShareRegisteredFallbacks() throws {
    let first = try DefaultsFixture()
    defer { first.cleanUp() }
    let second = try DefaultsFixture()
    defer { second.cleanUp() }
    let sharedKey = first.key("shared-probe")

    first.defaults.register(defaults: [sharedKey: true])
    #expect(second.defaults.bool(forKey: sharedKey))

    second.defaults.register(defaults: [sharedKey: false])
    #expect(first.defaults.bool(forKey: sharedKey) == false)
    #expect(first.defaults.persistentDomain(
        forName: first.suiteName)?[sharedKey] == nil)
}

There is no race to win here. As with testing async code without sleeping, we establish the order instead of guessing when work ran. The second registration changes the fallback visible through the first instance. The final assertion confirms that the first suite has no saved value for this key.

In two independently scheduled tests, that same sequence can happen between registration and assertion. Foundation’s thread-safe methods do not make the sequence private to one test.

Inject the key as well as the store

The distinction between registering and saving defaults has a longstanding accepted answer. We want to preserve that distinction: a user’s explicit choice overrides the fallback, and resetting the choice reveals the fallback again.

Here is a small settings wrapper. The production key remains stable. Tests can supply a different key without changing how values are read, saved or removed:

nonisolated struct HintSettings {
    static let showHintsKey = "showHints"

    private let defaults: UserDefaults
    private let key: String

    init(defaults: UserDefaults, key: String = HintSettings.showHintsKey) {
        self.defaults = defaults
        self.key = key
    }

    var showsHints: Bool {
        defaults.bool(forKey: key)
    }

    func setShowsHints(_ value: Bool) {
        defaults.set(value, forKey: key)
    }

    func reset() {
        defaults.removeObject(forKey: key)
    }
}

In the app, register the fallback for HintSettings.showHintsKey at startup and construct HintSettings(defaults: .standard), or use your actual shared suite. Keep registration at that composition point rather than having every settings wrapper register its own competing defaults.

The extra initializer argument is a test seam, not a new user setting. Do not generate random production keys: saved choices must still be found on the next launch. For a larger settings store, inject a small collection of keys instead of adding a separate argument to every method.

Now test both fallback values. Each parameterized invocation creates its own fixture and key. Do not move the fixture into a shared static property:

@Test(arguments: [true, false])
nonisolated func resetRevealsRegisteredFallback(fallback: Bool) throws {
    let fixture = try DefaultsFixture()
    defer { fixture.cleanUp() }
    let key = fixture.key("showHints")
    fixture.defaults.register(defaults: [key: fallback])
    let settings = HintSettings(defaults: fixture.defaults, key: key)

    #expect(settings.showsHints == fallback)

    settings.setShowsHints(!fallback)
    #expect(settings.showsHints == !fallback)
    #expect((fixture.defaults.persistentDomain(
        forName: fixture.suiteName)?[key] as? Bool) == !fallback)

    settings.reset()
    #expect(fixture.defaults.persistentDomain(
        forName: fixture.suiteName)?[key] == nil)
    #expect(settings.showsHints == fallback)
}

Checking both true and false matters. A missing Boolean also reads as false, so a test that only expects false can accidentally pass without exercising registration at all. The saved-domain assertions separately prove that setting writes a choice and resetting removes it.

This tests real Foundation behavior. For business logic that merely consumes preferences, an injected value or fake store may be simpler. Keep a few real-store tests for the behavior a fake cannot establish.

Clean up only what the fixture owns

cleanUp() removes the fixture’s named persistent domain. It deliberately does not clear the process’s registration domain. Registered keys remain in memory until the test process exits; because every fixture uses a new namespace, later cases do not reuse them.

Do not “fix” that by saving the entire registration dictionary in setup and restoring it in teardown. Another test may register a key between those operations. Restoring the old dictionary would erase that test’s work. Clearing all registered defaults has the same problem.

This fixture is intended for bounded test runs, not a long-lived service that creates unlimited registrations. It also isn’t a sandbox for every defaults domain: launch arguments, managed settings and other lookup sources still exist. The unique keys keep these tests away from the app’s ordinary keys. Code that insists on a fixed production key needs a separately controlled test process or a different dependency seam.

There is also no disk-flush wait here. We are testing reads and writes inside one process, not durability across a crash or visibility in an app extension. Those need separate integration tests.

Serialization is a narrower tool

Adding .serialized to one Swift Testing suite runs the tests inside that suite one at a time. It does not stop unrelated suites from running alongside it. Apple spells out that scope in Running tests serially or in parallel.

Serialization can be useful when a test deliberately exercises a shared resource. Every user of that resource must participate in the same isolation arrangement. A fixture with its own suite and keys is usually easier to reason about for independent preference cases.

The complete sample contains these exact examples plus checks for persistent-domain independence, repeated registrations and cleanup while another fixture remains active. Unzip it and run swift test; its README includes the native iOS test command.

Verified with Xcode 27.2 and Swift 6.4.2: the exact examples and additional checks pass on macOS 27.2 and an iOS 27.2 simulator, under ordinary and MainActor-default isolation. Each configuration runs eight test functions covering 40 cases. The sample targets macOS 14 and iOS 17; those older runtimes and physical devices were not part of this verification.

When a preference test passes alone and fails with its neighbors, inspect what it actually shares. A different suite name solves only the saved-domain part of that problem.