Created
June 8, 2017 22:01
-
-
Save jemmons/4c4bfb7feda08ecdbf74cee808a52b2c to your computer and use it in GitHub Desktop.
Turning JSON into URLQueryParams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func f(_ jsonValue: Any, prefix: String? = nil) throws -> [URLQueryItem] { | |
var items: [URLQueryItem] = [] | |
switch jsonValue { | |
case let d as Dictionary<String, Any>: | |
try d.forEach { | |
let newPrefix = prefix == nil ? $0.key : prefix! + "[\($0.key)]" | |
items.append(contentsOf: try f($0.value, prefix: newPrefix)) | |
} | |
case let a as Array<Any>: | |
guard let somePrefix = prefix else { | |
throw(ParamsError.invalidTopLevelType) | |
} | |
try a.forEach { it in | |
items.append(contentsOf: try f(it, prefix: somePrefix + "[]")) | |
} | |
default: | |
guard let somePrefix = prefix else { | |
throw(ParamsError.invalidTopLevelType) | |
} | |
items.append(URLQueryItem(name: somePrefix, value: String(describing: jsonValue))) | |
} | |
return items | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment