I have a dictionary as [String:Any]
.Now i want to convert this dictionary keys & value as key=value&key=value
.I have created below extensio
protocol ParametersConvertible {
func asParameters() -> [String:Any]
}
protocol QueryStringConvertible {
func asQuery() -> String
}
extension QueryStringConvertible where Self: ParametersConvertible {
func asQuery() -> String {
var queries: [URLQueryItem] = []
for (key, value) in self.asParameters() {
queries.append(.init(name: key, value: "\(value)"))
}
guard var components = URLComponents(string: "") else {
return ""
}
components.queryItems = queries
return components.percentEncodedQuery ?? ""
}
}
For anyone that wants the "short, short" version.
Condensed using map, you don't need the forEach or for loops. Also protocol constrained for type enforcement on the dictionary.
extension Dictionary where Key : StringProtocol, Value : StringProtocol {
var queryString: String {
self.map { "\($0)=\($1)" }.joined(separator: "&")
}
}
Another Swift-esque approach:
let params = [
"id": 2,
"name": "Test"
]
let urlParams = params.flatMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
Same as @KKRocks with update for swift 4.1.2
func queryItems(dictionary: [String:Any]) -> String {
var components = URLComponents()
print(components.url!)
components.queryItems = dictionary.map {
URLQueryItem(name: $0, value: String(describing: $1))
}
return (components.url?.absoluteString)!
}
extension Dictionary {
var queryString: String? {
return self.reduce("") { "\($0!)\($1.0)=\($1.1)&" }
}
}
Try this :
func queryItems(dictionary: [String:Any]) -> String {
var components = URLComponents()
print(components.url!)
components.queryItems = dictionary.map {
URLQueryItem(name: $0, value: $1)
}
return (components.url?.absoluteString)!
}