Type-safe property wrappers and helpers for UserDefaults, from plain structs to SwiftUI views and @Observable models.
- Supports every type
UserDefaultssupports, plusRawRepresentableenums,Codabletypes, Core Graphics value types and more - Works with optional and non-optional values
- Registers default values automatically
- Speaks Swift 6 strict concurrency
import DefaultsWrapper
struct Game {
@Defaults("NumberOfPlayers") var playerCount: Int = 3
}
struct SettingsView: View {
@Preference("PlayerName") var playerName: String = "Red" // Like AppStorage
@SavedState("StartingPosition") var startPos: CGPoint = .zero // Like State, persisted
...
}
@MainActor @Observable
final class Settings {
var volume: Double = 0.5
@ObservationIgnored private var binding: DefaultObservable<Settings, Double>?
init() {
binding = DefaultObservable(self, keyPath: \.volume, key: "Volume")
}
}| Type | Use it for |
|---|---|
@Defaults |
Plain Swift types |
DefaultsValue |
A single value you pass around |
@Preference |
SwiftUI views that refresh when the value changes |
@SavedState / @LoadedState |
SwiftUI views that own the value |
DefaultObservable |
Binding a property of an @Observable model |
@PublishedPreference |
ObservableObject types |
UserDefaultsKeyName |
Declaring keys once instead of repeating string literals |
- Swift 6.2+
- macOS 15+, iOS 18+, tvOS 18+, watchOS 10+
Need older OS versions? Use 2.x.
Add DefaultsWrapper to your Package.swift:
.package(url: "https://github.com/Pyroh/DefaultsWrapper", .upToNextMajor(from: "3.0.0"))It depends on OptionalType, fetched automatically.
The full documentation is a DocC catalog: open the package in Xcode and choose Product > Build Documentation. It covers supported types, optionals, default value registration, adding your own types and migrating from 2.x.
MIT. See LICENSE.