Skip to content

Latest commit

 

History

History
74 lines (53 loc) · 2.58 KB

README.md

File metadata and controls

74 lines (53 loc) · 2.58 KB

Swift Platforms Swift Package Manager compatible License

DefaultsWrapper

Type-safe property wrappers and helpers for UserDefaults, from plain structs to SwiftUI views and @Observable models.

  • Supports every type UserDefaults supports, plus RawRepresentable enums, Codable types, 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")
    }
}

What's in the box

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

Requirements

  • Swift 6.2+
  • macOS 15+, iOS 18+, tvOS 18+, watchOS 10+

Need older OS versions? Use 2.x.

Installation

Add DefaultsWrapper to your Package.swift:

.package(url: "https://github.com/Pyroh/DefaultsWrapper", .upToNextMajor(from: "3.0.0"))

It depends on OptionalType, fetched automatically.

Documentation

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.

License

MIT. See LICENSE.