ObservableDefaults connects Swift Observation to UserDefaults and iCloud key-value storage through class macros.
English | 中文
Managing many UserDefaults keys in SwiftUI often creates repetitive code, while @AppStorage is centered on individual values and does not cover iCloud key-value synchronization. Observation also benefits from property-level tracking so unrelated changes do not invalidate a whole view.
ObservableDefaults uses macros to connect model properties to UserDefaults or NSUbiquitousKeyValueStore, while preserving precise Observation updates and handling changes originating outside the model.
For the design background and an in-depth comparison with @AppStorage, read UserDefaults and Observation.
@ObservableDefaultspersists observable properties inUserDefaults.@ObservableCloudsynchronizes observable properties throughNSUbiquitousKeyValueStore.- External storage changes produce property-level Observation updates.
- Custom keys, suite names, and prefixes support application-specific storage layouts.
- Optional, Codable, and RawRepresentable values are supported through documented storage rules.
- Observe-first mode lets a model opt properties into persistence explicitly.
- Development mode isolates cloud-backed models for previews and tests.
Add ObservableDefaults with Swift Package Manager:
dependencies: [
.package(
url: "https://github.com/fatbobman/ObservableDefaults.git",
from: "1.8.8"
)
]Declare a class whose properties are observable and backed by UserDefaults:
import ObservableDefaults
@ObservableDefaults
final class Settings {
var username = "Guest"
var launchCount = 0
}
let settings = Settings()
settings.launchCount += 1- Want to configure local and cloud macros, keys, storage types, or observe-first mode? Read the Usage Guide.
- Want to understand defaults, previews, CI, actor isolation, App Groups, or cloud constraints? Read Behavior and Integration Notes.
ObservableDefaults is available under the MIT license. See the LICENSE file for more info.
Fatbobman (肘子) — Blog: fatbobman.com · X: @fatbobman
If this project helps you, please consider supporting my work:
- 📮 Subscribe to Fatbobman's Swift Weekly — fresh Swift and Apple-ecosystem insights every week
- ☕️ Buy Me a Coffee