Skip to content

2.0.0

Latest

Choose a tag to compare

@kylehughes kylehughes released this 20 Nov 23:15
e1eb07b

PersistentKeyValueKit 2.0.0 adds typed key migration within and between stores, checked format-aware conversion on representations and primitive types, PersistentKeyProtocol routing on InMemoryPersistentKeyValueStore, updated URL and collection rules, observation refinements across SwiftUI, AsyncSequence, Combine, and Foundation stores, and an Apple privacy manifest. Custom PersistentKeyValueRepresentation, PrimitiveKeyValuePersistible, and PersistentKeyValueStore conformances require new members, and URL, collection, and in-memory optional semantics change; see Breaking Changes and Upgrade Guide. See the API documentation for the contracts and edge cases of the new APIs.

What's New

Key Migration

PersistentKeyValueStore adds copy and move overloads for a single key, a single PersistentKeyMigrationItem, a heterogeneous array ([any PersistentKeyProtocol]), or a labeled array (items: [PersistentKeyMigrationItem]). Each requires onConflict: and tracking: and returns a PersistentKeyMigrationReport. Create any named UserDefaults suite that participates in a migration with UserDefaults.migratable(suiteName:).

See Migrating Values Between Stores for a worked example. See copy, move, PersistentKeyMigrationTracking, PersistentKeyMigrationReport, and PersistentKeyMigrationError for retries, failure stages, completion markers, iCloud timing, and coordination.

Checked Representation Conversion

PersistentKeyValueRepresentation and PrimitiveKeyValuePersistible add throwing decode(storageObject:format:) and encode(_:format:) / encode(format:) methods taking PersistentKeyValueStorageFormat (.propertyList, .userDefaults, or .ubiquitousKeyValueStore). Ordinary get and set stay non-throwing, and conversion can run more than once for the same value. Built-in conversion failures throw PersistentKeyValueConversionError, while Foundation and codec errors can also propagate.

Built-in checked collection decoding fails on an undecodable element or entry where an ordinary Dictionary read omits it, though a custom container reader can filter values and custom representations run their container methods as written during checked conversion. URL conversion supports absolute URLs and relative references, and checked .userDefaults encoding rejects a file URL whose stored path cannot reproduce its absoluteString. See PersistentKeyValueRepresentation, Array, and Dictionary for the collection-conversion contracts.

In-Memory Store Key Routing

InMemoryPersistentKeyValueStore now routes get(_:), set(_:to:), and remove(_:) through PersistentKeyProtocol (get(from:), set(to:in:), remove(from:)), letting custom keys gate or clamp in-memory access as they do for Foundation stores. A key's value must live under id in every store so observation and migration act on the same entry.

Privacy Manifest

The PersistentKeyValueKit target bundles PrivacyInfo.xcprivacy declaring UserDefaults access (NSPrivacyAccessedAPICategoryUserDefaults) with reasons CA92.1 (app-sandbox preferences) and 1C8F.1 (app-group preferences).

Breaking Changes and Upgrade Guide

2.0.0 requires iOS 16, tvOS 16, or watchOS 9 or newer; the macOS 13 and visionOS 1 minimums are unchanged. Every API is now available on every supported OS version: the NSUbiquitousKeyValueStore APIs no longer require a watchOS 9 availability check, and CodablePersistentKeyValueRepresentation() and a persistentKeyValueRepresentation property that returns some PersistentKeyValueRepresentation<Self> no longer require an iOS 16 one. You can remove availability annotations that only guarded those uses.

Upgrading directly from 1.0.0 also requires the changes 1.1.0 introduced: a Swift 6.2 or newer toolchain, macOS 13 or newer for macOS builds, and, in generic code that calls ProxyPersistentKeyValueRepresentation's init(other:to:from:), an Other.Proxy: SendableMetatype constraint (the representation protocol already satisfies the initializer's bound on Other).

1. Direct PersistentKeyValueRepresentation Conformances

PersistentKeyValueRepresentation now requires decode(storageObject:format:) and encode(_:format:). Its eight store- and container-specific get and set methods default to those two methods, while existing overrides still apply to ordinary reads and writes. ProxyPersistentKeyValueRepresentation, RawRepresentablePersistentKeyValueRepresentation, CodablePersistentKeyValueRepresentation, and LosslessStringConvertiblePersistentKeyValueRepresentation already provide both. A ProxyPersistentKeyValueRepresentationProtocol conformer inherits checked conversion. If it overrides ordinary store access, verify in each supported format that checked decoding reads objects its setter wrote and that its ordinary getter reads objects checked encoding produces. A customized dictionary-entry setter also needs the registered-format step below.

  • Implement decode(storageObject:format:) and encode(_:format:): Make decode accept the immutable Foundation form of each object your existing setter or encoder produces, and make encode produce objects your ordinary getter can read, because Foundation migration validates encoded objects with the checked methods while later ordinary reads still use your getter. Do not mutate objects after returning them from encode or writing them with set.
  • Handle nil encodings: Default Foundation setters still remove the entry when encode returns nil, and collections apply their own encoding rules. After a successful migration write to UserDefaults or NSUbiquitousKeyValueStore, the destination entry is absent only when the key's top-level encoding is nil and the value is nil at an actual Optional layer; any other top-level value that encodes to nil fails that item at .prepare, writing neither entry. A type-changing UserDefaults replacement can temporarily remove the old entry before storing the new object.
  • Preserve registered default formats: In 1.x, UserDefaults.register(_:) registered every representation's default through its dictionary-entry setter; in 2.0.0 it registers the result of checked .userDefaults encoding. If raw UserDefaults clients read a format your 1.x dictionary setter customized, reproduce it in .userDefaults encoding, even if a proxy customized only the dictionary-entry setter.
  • Support MainActor default isolation: In a target with MainActor default isolation, make the conversion witnesses and the members they call (such as Value.init(parsing:) below) usable from nonisolated code. Declaring the extension nonisolated covers the witnesses. Marking individual witnesses nonisolated can preserve the rest of the type's isolation:
nonisolated extension CustomRepresentation: PersistentKeyValueRepresentation {
    func decode(storageObject: Any, format: PersistentKeyValueStorageFormat) throws -> Value {
        guard let string = storageObject as? String, let value = Value(parsing: string) else {
            throw PersistentKeyValueConversionError.invalidStorageValue
        }
        return value
    }

    func encode(_ value: Value, format: PersistentKeyValueStorageFormat) throws -> Any? {
        value.serializedString
    }
}

2. Custom PrimitiveKeyValuePersistible Conformances

PrimitiveKeyValuePersistible now requires static func decode(storageObject:format:) and func encode(format:). Its eight store- and container-specific get and set methods default to those two methods (using .propertyList for containers), while existing overrides still apply to ordinary reads and writes. Built-in primitive types (Bool, Int, Float, Double, String, Data, URL, Array, and Dictionary) and Optional require no changes.

  • Implement decode(storageObject:format:) and encode(format:): Follow the same decode and encode rules as for representations. Custom primitives that used the 1.x container defaults now write and read container elements through encode(format: .propertyList) and decode(storageObject:format: .propertyList), so decode must accept any objects 1.x persisted in containers.
  • Preserve registered default formats: If a primitive's 1.x dictionary-entry setter customized what UserDefaults.register(_:) stored and raw UserDefaults clients read it, reproduce that format in encode(format: .userDefaults).
  • Support MainActor default isolation: In a target with MainActor default isolation, make the conversion witnesses usable from nonisolated code. A nonisolated extension covers its witnesses. Also make the members they call usable from nonisolated code. When annotating members individually, include those callees:
nonisolated extension CustomPrimitive: PrimitiveKeyValuePersistible {
    static func decode(storageObject: Any, format: PersistentKeyValueStorageFormat) throws -> Self {
        Self(rawValue: try Int.decode(storageObject: storageObject, format: format))
    }

    func encode(format: PersistentKeyValueStorageFormat) throws -> Any? {
        NSNumber(value: rawValue)
    }
}

3. Custom PersistentKeyValueStore Conformances

PersistentKeyValueStore now requires var migrationEndpoint: PersistentKeyValueMigrationEndpoint { get throws }.

Forward your backing store's migrationEndpoint (try base.migrationEndpoint), or throw your own error if the store cannot migrate (copy and move propagate it unchanged). Forwarding makes migration read and write the backing store directly, bypassing the wrapper's and the keys' ordinary accessors. Any store used with observation must support concurrent access, including to mutable state a forwarding wrapper adds.

In a target with MainActor default isolation, a nonisolated function can pass the store to PersistentKeyValues, copy, or move only if its conformance is nonisolated. Marking a wrapper's protocol methods and migrationEndpoint nonisolated individually works only when every stored property and member they use is also usable from nonisolated code. For the wrapper below, declare nonisolated struct ForwardingStore:

extension ForwardingStore: PersistentKeyValueStore {
    var migrationEndpoint: PersistentKeyValueMigrationEndpoint {
        get throws {
            try base.migrationEndpoint
        }
    }
}

4. URL Storage and Validation

  • NSUbiquitousKeyValueStore format and 1.x iCloud sync: 1.x passed a raw URL (not a property-list type) to the NSUbiquitousKeyValueStore setter. Writing a URL there now stores url.absoluteString (String), while reading accepts String values or a raw URL if the store returns one. Because 1.x clients read URL keys with object(forKey:) as? URL, a URL written by a 2.0.0 device (String) and synced to a 1.x device causes the 1.x client to fall back to defaultValue.
  • UserDefaults registered defaults: 1.x registered a URL default as its absoluteString (String). In 2.0.0, UserDefaults.register(_:) registers a representable file URL as a path and a non-file URL as archive data, so raw string(forKey:) on a registered non-file URL default returns nil; use url(forKey:) for raw access. Typed reads of an unset key with a visible registered URL default also change: on macOS, the 1.2.3 typed getter read a registered HTTPS string as a local file path, while 2.0.0 returns the HTTPS URL.
  • Ordinary UserDefaults writes: Ordinary UserDefaults set still uses Foundation's URL setter and storage format, so a file URL with no path (such as file:) can remove the entry, and file://localhost stores an unreadable empty path. See the URL documentation for details.

5. All-or-Nothing Collection Writes and Container Contracts

In 1.x, failed collection writes could overwrite part of a collection. In 2.0.0, Array and Dictionary writes are all-or-nothing across UserDefaults, NSUbiquitousKeyValueStore, and property-list containers, leaving the store unchanged if any element or entry fails to encode, while omitting Optional nil elements and entries.

  • propertyListArray replacement: The built-in URL, Array, and Dictionary implementations of set(_:to: inout [Any]) appended to propertyListArray in 1.x and replace it in 2.0.0. The package passes an empty array to set(_:to:) and a dictionary missing dictionaryKey to set(_:to:in:), so a custom array hook can still append its encoded result. If the hook receives nonempty input and leaves the supplied array empty, 2.0.0 preserves the previous collection, where 1.x stored an empty array. To store an intentionally empty result, filter the input before calling set.
  • Container hook contracts: Array set(_:to:) hooks must build the encoded array separately, assign or append it to the empty array only after every element succeeds, and leave that array empty on failure. Dictionary set(_:to:in:) hooks must write only dictionaryKey. A custom writer that leaves its requested entry unwritten, or a nonoptional proxy whose to returns nil, now fails the whole dictionary write; filter intentionally omitted entries first, or use optional dictionary values.
  • Handover contract: Do not mutate an object (including mutable strings, data buffers, dictionary keys, and containers) after returning it from encode, returning it from a proxy to, or writing it via set; behavior is unspecified otherwise.
  • Reads: An ordinary Array read of built-in element representations is all-or-nothing, and an ordinary Dictionary read omits undecodable entries. Saving a decoded collection back replaces the stored one, so an older client can erase entries it could not decode. See Array and Dictionary for details.

6. Named UserDefaults Suites in Migrations

Create any named UserDefaults suite passed to copy, move, or .once(id:recordedIn:) with UserDefaults.migratable(suiteName:). Ordinary UserDefaults(suiteName:) instances keep working outside migrations, but throw PersistentKeyMigrationError.missingMigrationDomain if used in a migration. UserDefaults.standard requires a non-empty Bundle.main.bundleIdentifier, or migration throws .missingApplicationIdentifier.

7. PersistentDebugKey, In-Memory Optionals, and Key Access

  • InMemoryPersistentKeyValueStore routes through PersistentKeyProtocol, so it applies PersistentDebugKey's Release lock and skips migration with .keyDisabled. Custom PersistentKeyProtocol types get in-memory defaults.
  • Unset or removed optional keys in InMemoryPersistentKeyValueStore now return key.defaultValue (even when non-nil), whereas setting an optional key to nil through the default in-memory setter records an explicit nil that get(_:) returns. A key can override that setter, and PersistentDebugKey ignores the write in Release builds.
  • The default in-memory setter now preserves the original mutable Foundation array and mutable dictionaries that 1.x bridged to [String: Any?]. Mutating a retained object changes later reads without notifying observers. If compacting a Swift array or String-keyed dictionary of optionals would make it unreadable as the key's value type, the setter keeps the original collection, including its nil members; such a write could read back as the key's default in 1.x.
  • PersistentKey and PersistentDebugKey Equatable and Hashable now compare id by literal UTF-16 code units, and PersistentKeyUIObservableObject.key is now public private(set) var.

Behavior Changes from 1.x

Key Identity

UserDefaults, NSUbiquitousKeyValueStore, PersistentKey, and PersistentDebugKey compare and hash key identifiers by literal UTF-16 code units, so composed and decomposed spellings, and identifiers differing only in unpaired surrogates, stay distinct keys. InMemoryPersistentKeyValueStore merges them, so a test that needs them distinct must use a Foundation store. Because PersistentKeyProtocol.ID is String (which equates canonically equivalent spellings), use ForEach(keys, id: \.id.utf8CString) to keep canonically equivalent spellings distinct in SwiftUI; see PersistentKeyProtocol.id for the limits of that workaround.

SwiftUI

@PersistentValue adopts the latest key on each view update and replaces its observation when the key identifier or selected store changes. An explicit store: takes precedence over the defaultPersistentKeyValueStore environment value. A $binding captures the active key and store when created, so a retained binding keeps reading and writing its original key and store after the view switches.

Assigning a different store to PersistentKeyUIObservableObject updates observation, stops notifications from the previous store, and sends objectWillChange; reassigning the same store instance keeps its existing registration. A write to PersistentKeyUIObservableObject.value uses the key and store selected when its setter starts, even if a subscriber switches stores. Reading value without a store returns key.defaultValue, and writing without a store is discarded and asserts in Debug builds.

Async and Combine Observation

PersistentKeyValues emits values read from the store in read order, defaulting to .bufferingNewest(1), and several store change reports can produce one read and one emitted value. When next() observes cancellation of the iterating Task, it deregisters, releases pending and buffered values, and returns nil.

With initial emission enabled, PersistentKeyValuePublisher reads the current value on subscription and delivers it on first demand; a changes-only subscription waits for a reported change. Delivery is serial per subscription, can occur on a background thread, and does not schedule on a queue, so use .receive(on: DispatchQueue.main) before updating UI. During receive(subscription:), only the subscribing thread delivers, so blocking there while waiting for another thread to deliver a value deadlocks.

Foundation Stores

UserDefaults keys that key-value observation cannot observe (empty keys, a leading @, a ., NUL, and valueForKey: / ValueForKey:) now observe through UserDefaults.didChangeNotification across all observation APIs. Changes are sampled, so rapid writes coalesce and a change undone before sampling can emit nothing. Other UserDefaults keys keep key-value observation and see cross-process changes, though Foundation posts nothing for a write that compares equal under Foundation equality (such as Int64 over an equal Int32).

A manual UserDefaults observer receives observeValue(forKeyPath:of:change:context:) for its registered keys only. A manual NSUbiquitousKeyValueStore observer's selector, which 1.x called for every change notification from the store, now receives only notifications that list its registered literal key, report an account change, or have a missing or unusable changed-keys list. The package treats an account change or a notification without a usable changed-keys list as potentially affecting every observed key on that store.

Manual deregistration removes one native UserDefaults key-value observation registration per call, whereas notification-backed keys and the iCloud and in-memory stores remove every registration with the same observer, key, and context. In NSUbiquitousKeyValueStore, deregistration did nothing in 1.0.0 and removed all of an observer's registrations in 1.1.0 through 1.2.3, so each key-and-context pair now needs its own call. NotificationCenter.default.removeObserver(_:) no longer stops a package-registered iCloud observer as it did in 1.x; call deregister(_:for:context:) for each original key and context instead. In memory, an earlier callback can now deregister a later observer before its pending callback runs. Deregister before releasing a manual observer, because a notification-backed key can keep being sampled until its registration is removed.

Registration and Launch Arguments

UserDefaults.register(_:) and registerDefault(in:) encode defaults with .userDefaults format and skip a default that fails checked encoding. Typed reads decode a visible registered object, so the result can differ from defaultValue when encoding loses information (such as an array encoding that omits nil elements). register(_:) preserves literal UTF-16 keys, whereas registerDefault(in:) fills a Swift dictionary that merges canonically equivalent spellings. The registration domain is volatile, so register on every launch in each app or extension process. Every UserDefaults instance in that process shares the domain, so registering the same identifier in another suite can replace its fallback.

Launch-argument coercion applies only when the visible value is the literal key's UserDefaults.argumentDomain string and no managed preference overrides it, so a launch argument for one Unicode spelling does not coerce a value stored under another.