Skip to content

Commit 4fa2f61

Browse files
Shibo LyuShibo Lyu
authored andcommitted
doc: Document TypedUserDefaults usage and update docs
1 parent b94a694 commit 4fa2f61

File tree

2 files changed

+48
-4
lines changed

2 files changed

+48
-4
lines changed
Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
# ``TypedAppStorage``
22

3-
A type-safe way to save and read complex data structures from `@AppStorage`.
3+
A type-safe way to save and read complex data structures from `@AppStorage` and `UserDefaults`.
44

5-
- Use actual `@AppStorage` underneath
6-
- Support any `Codable` data
5+
- Use actual `@AppStorage` or `UserDefaults` underneath
6+
- Support any `Codable & Sendable` data
77
- Define the key in the data model
88

99
## Topics
1010

1111
### Essentials
1212

1313
- <doc:GettingStarted>
14-
- ``TypedAppStorage``
1514
- ``TypedAppStorageValue``
15+
- ``TypedAppStorage``
16+
- ``TypedUserDefaults``

Sources/TypedAppStorage/Documentation.docc/GettingStarted.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,46 @@ In some cases it might make sense to specify a different default value than the
6969
```
7070

7171
And you can specify a different store just like `@AppStorage`, if you're using things like App Groups.
72+
73+
### Use outside SwiftUI Views
74+
75+
When you're not in a SwiftUI context, you can use ``TypedUserDefaults`` to access the same type-safe storage:
76+
77+
```swift
78+
let typedDefaults = TypedUserDefaults.standard
79+
80+
// Reading values
81+
let currentFruit = typedDefaults.object(of: PreferredFruit.self)
82+
83+
// Writing values
84+
let newFruit = PreferredFruit(.moderate, .pear)
85+
typedDefaults.set(newFruit)
86+
```
87+
88+
Just like `@TypedAppStorage`, the key and default value are automatically inferred from the type's ``TypedAppStorageValue`` conformance.
89+
90+
You can also override the key or default value if needed:
91+
92+
```swift
93+
// Use a different key
94+
let specialFruit = typedDefaults.object(
95+
of: PreferredFruit.self,
96+
forKey: "specialPreferredFruit"
97+
)
98+
99+
// Use a different default value
100+
let fruitWithCustomDefault = typedDefaults.object(
101+
of: PreferredFruit.self,
102+
defaultValue: .init(.somewhatStale, .banana)
103+
)
104+
```
105+
106+
And you can use a different UserDefaults store, just like with the SwiftUI property wrapper:
107+
108+
```swift
109+
let groupDefaults = TypedUserDefaults(
110+
userDefaults: UserDefaults(suiteName: "group.com.example.app")!
111+
)
112+
let sharedFruit = groupDefaults.object(of: PreferredFruit.self)
113+
```
114+

0 commit comments

Comments
 (0)