@@ -7,9 +7,10 @@ enum URLEncodedFormNode: CustomStringConvertible, Equatable {
7
7
/// holds an array of nodes
8
8
case array( Array )
9
9
10
- enum Error : Swift . Error {
10
+ enum Error : Swift . Error , Equatable {
11
11
case failedToDecode( String ? = nil )
12
12
case notSupported
13
+ case invalidArrayIndex( Int )
13
14
}
14
15
15
16
/// Initialize node from URL encoded form data
@@ -51,7 +52,7 @@ enum URLEncodedFormNode: CustomStringConvertible, Equatable {
51
52
/// function for create `URLEncodedFormNode` from `KeyParser.Key.Type`
52
53
func createNode( from key: KeyParser . KeyType ) -> URLEncodedFormNode {
53
54
switch key {
54
- case . array:
55
+ case . array, . arrayWithIndices :
55
56
return . array( . init( ) )
56
57
case . map:
57
58
return . map( . init( ) )
@@ -84,6 +85,11 @@ enum URLEncodedFormNode: CustomStringConvertible, Equatable {
84
85
// currently don't support arrays and maps inside arrays
85
86
throw Error . notSupported
86
87
}
88
+ case ( . array( let array) , . arrayWithIndices( let index) ) :
89
+ guard keys. count == 0 , array. values. count == index else {
90
+ throw Error . invalidArrayIndex ( index)
91
+ }
92
+ array. values. append ( . leaf( value) )
87
93
default :
88
94
throw Error . failedToDecode ( )
89
95
}
@@ -168,7 +174,7 @@ enum URLEncodedFormNode: CustomStringConvertible, Equatable {
168
174
169
175
/// Parse URL encoded key
170
176
enum KeyParser {
171
- enum KeyType : Equatable { case map( Substring ) , array }
177
+ enum KeyType : Equatable { case map( Substring ) , array, arrayWithIndices ( Int ) }
172
178
173
179
static func parse( _ key: String ) -> [ KeyType ] ? {
174
180
var index = key. startIndex
@@ -186,13 +192,19 @@ enum KeyParser {
186
192
index = key. index ( after: index)
187
193
// an open bracket is unexpected
188
194
guard index != key. endIndex else { return nil }
195
+
189
196
if key [ index] == " ] " {
190
197
values. append ( . array)
191
198
index = key. index ( after: index)
192
199
} else {
193
200
// an open bracket is unexpected
194
201
guard let bracketIndex = key [ index... ] . firstIndex ( of: " ] " ) else { return nil }
195
- values. append ( . map( key [ index..< bracketIndex] ) )
202
+ // If key can convert to an integer assume it is an array index
203
+ if let index = Int ( key [ index..< bracketIndex] ) {
204
+ values. append ( . arrayWithIndices( index) )
205
+ } else {
206
+ values. append ( . map( key [ index..< bracketIndex] ) )
207
+ }
196
208
index = bracketIndex
197
209
index = key. index ( after: index)
198
210
}
0 commit comments