As Alexander suggested this is a solution with URLComponents and URLQueryItem
import Foundation let dict: [String: Any] = [ "foo": "whatever", "this": "that", "category": [ "cat1", "cat2" ] ] var queryItems = [URLQueryItem]() for (key, value) in dict { if let strings = value as? [String] { queryItems.append(contentsOf: strings.map{ URLQueryItem(name: key, value: $0) }) } else { queryItems.append(URLQueryItem(name: key, value: value as? String)) } } var urlComponents = URLComponents(string: "http://myserver.com")! urlComponents.queryItems = queryItems let url = urlComponents.url! print(url.absoluteString) // => http://myserver.com?this=that&foo=whatever&category=cat1&category=cat2
A similar solution, but simpler, using flatMap:
let queryItems = dict.flatMap { key, value -> [URLQueryItem] in if let strings = value as? [String] { return strings.map{ URLQueryItem(name: key, value: $0) } } else { return [URLQueryItem(name: key, value: value as? String)] } } var urlComponents = URLComponents(string: "http://myserver.com")! urlComponents.queryItems = queryItems let url = urlComponents.url! print(url.absoluteString) // => http://myserver.com?this=that&foo=whatever&category=cat1&category=cat2
NSURLComponentsandNSQueryItem. It does exactly what you want: stackoverflow.com/a/39770846/3141234