@@ -82,6 +82,28 @@ extension URIDecoder {
82
82
}
83
83
}
84
84
85
+ /// Attempt to decode an object from an URI string, if present.
86
+ ///
87
+ /// Under the hood, `URIDecoder` first parses the string into a
88
+ /// `URIParsedNode` using `URIParser`, and then uses
89
+ /// `URIValueFromNodeDecoder` to decode the `Decodable` value.
90
+ ///
91
+ /// - Parameters:
92
+ /// - type: The type to decode.
93
+ /// - key: The key of the decoded value. Only used with certain styles
94
+ /// and explode options, ignored otherwise.
95
+ /// - data: The URI-encoded string.
96
+ /// - Returns: The decoded value.
97
+ func decodeIfPresent< T: Decodable > (
98
+ _ type: T . Type = T . self,
99
+ forKey key: String = " " ,
100
+ from data: String
101
+ ) throws -> T ? {
102
+ try withCachedParser ( from: data) { decoder in
103
+ try decoder. decodeIfPresent ( type, forKey: key)
104
+ }
105
+ }
106
+
85
107
/// Make multiple decode calls on the parsed URI.
86
108
///
87
109
/// Use to avoid repeatedly reparsing the raw string.
@@ -133,4 +155,29 @@ struct URICachedDecoder {
133
155
)
134
156
return try decoder. decodeRoot ( )
135
157
}
158
+
159
+ /// Attempt to decode an object from an URI-encoded string, if present.
160
+ ///
161
+ /// Under the hood, `URICachedDecoder` already has a pre-parsed
162
+ /// `URIParsedNode` and uses `URIValueFromNodeDecoder` to decode
163
+ /// the `Decodable` value.
164
+ ///
165
+ /// - Parameters:
166
+ /// - type: The type to decode.
167
+ /// - key: The key of the decoded value. Only used with certain styles
168
+ /// and explode options, ignored otherwise.
169
+ /// - Returns: The decoded value.
170
+ func decodeIfPresent< T: Decodable > (
171
+ _ type: T . Type = T . self,
172
+ forKey key: String = " "
173
+ ) throws -> T ? {
174
+ let decoder = URIValueFromNodeDecoder (
175
+ node: node,
176
+ rootKey: key [ ... ] ,
177
+ style: configuration. style,
178
+ explode: configuration. explode,
179
+ dateTranscoder: configuration. dateTranscoder
180
+ )
181
+ return try decoder. decodeRootIfPresent ( )
182
+ }
136
183
}
0 commit comments