mirror of
https://github.com/laosb/TypedAppStorage.git
synced 2025-06-23 09:41:08 +00:00
doc: Document TypedUserDefaults usage and update docs
This commit is contained in:
parent
b94a694193
commit
4fa2f61532
2 changed files with 48 additions and 4 deletions
|
@ -1,9 +1,9 @@
|
|||
# ``TypedAppStorage``
|
||||
|
||||
A type-safe way to save and read complex data structures from `@AppStorage`.
|
||||
A type-safe way to save and read complex data structures from `@AppStorage` and `UserDefaults`.
|
||||
|
||||
- Use actual `@AppStorage` underneath
|
||||
- Support any `Codable` data
|
||||
- Use actual `@AppStorage` or `UserDefaults` underneath
|
||||
- Support any `Codable & Sendable` data
|
||||
- Define the key in the data model
|
||||
|
||||
## Topics
|
||||
|
@ -11,5 +11,6 @@ A type-safe way to save and read complex data structures from `@AppStorage`.
|
|||
### Essentials
|
||||
|
||||
- <doc:GettingStarted>
|
||||
- ``TypedAppStorage``
|
||||
- ``TypedAppStorageValue``
|
||||
- ``TypedAppStorage``
|
||||
- ``TypedUserDefaults``
|
||||
|
|
|
@ -69,3 +69,46 @@ In some cases it might make sense to specify a different default value than the
|
|||
```
|
||||
|
||||
And you can specify a different store just like `@AppStorage`, if you're using things like App Groups.
|
||||
|
||||
### Use outside SwiftUI Views
|
||||
|
||||
When you're not in a SwiftUI context, you can use ``TypedUserDefaults`` to access the same type-safe storage:
|
||||
|
||||
```swift
|
||||
let typedDefaults = TypedUserDefaults.standard
|
||||
|
||||
// Reading values
|
||||
let currentFruit = typedDefaults.object(of: PreferredFruit.self)
|
||||
|
||||
// Writing values
|
||||
let newFruit = PreferredFruit(.moderate, .pear)
|
||||
typedDefaults.set(newFruit)
|
||||
```
|
||||
|
||||
Just like `@TypedAppStorage`, the key and default value are automatically inferred from the type's ``TypedAppStorageValue`` conformance.
|
||||
|
||||
You can also override the key or default value if needed:
|
||||
|
||||
```swift
|
||||
// Use a different key
|
||||
let specialFruit = typedDefaults.object(
|
||||
of: PreferredFruit.self,
|
||||
forKey: "specialPreferredFruit"
|
||||
)
|
||||
|
||||
// Use a different default value
|
||||
let fruitWithCustomDefault = typedDefaults.object(
|
||||
of: PreferredFruit.self,
|
||||
defaultValue: .init(.somewhatStale, .banana)
|
||||
)
|
||||
```
|
||||
|
||||
And you can use a different UserDefaults store, just like with the SwiftUI property wrapper:
|
||||
|
||||
```swift
|
||||
let groupDefaults = TypedUserDefaults(
|
||||
userDefaults: UserDefaults(suiteName: "group.com.example.app")!
|
||||
)
|
||||
let sharedFruit = groupDefaults.object(of: PreferredFruit.self)
|
||||
```
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue