You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
let user =tryKeyValuDecoder().decode(User.self, from: [["id":1, "name":"Herbert"], ["id:"2])
56
56
```
57
57
58
+
## Nil Encoding/Decoding Strategy
59
+
60
+
The encoding of `Optional.none` can be adjusted by setting the strategy.
61
+
62
+
The default strategy preserves `Optional.none`:
63
+
64
+
```swift
65
+
let encoder =KeyValueEncoder()
66
+
encoder.strategy= .default
67
+
68
+
// [1, 2, nil, 3]
69
+
let any =try encoder.encode([1, 2, Int?.none, 3])
70
+
```
71
+
72
+
Compatibility with [`PropertyListEncoder`](https://developer.apple.com/documentation/foundation/propertylistencoder) is preserved using a placeholder string:
73
+
74
+
```swift
75
+
encoder.strategy= .stringNull
76
+
77
+
// [1, 2, "$null", 3]
78
+
let any =try encoder.encode([1, 2, Int?.none, 3])
79
+
```
80
+
81
+
Compatibility with [`JSONSerialization`](https://developer.apple.com/documentation/foundation/jsonserialization) is preserved using [`NSNull`](https://developer.apple.com/documentation/foundation/nsnull):
82
+
83
+
```swift
84
+
encoder.strategy= .nsNull
85
+
86
+
// [1, 2, NSNull(), 3]
87
+
let any =try encoder.encode([1, 2, Int?.none, 3])
88
+
```
89
+
90
+
Nil values can also be completely removed:
91
+
92
+
```swift
93
+
encoder.strategy= .removed
94
+
95
+
// [1, 2, 3]
96
+
let any =try encoder.encode([1, 2, Int?.none, 3])
97
+
```
98
+
58
99
## UserDefaults
59
100
Encode and decode [`Codable`](https://developer.apple.com/documentation/swift/codable) types with [`UserDefaults`](https://developer.apple.com/documentation/foundation/userdefaults):
0 commit comments