Вы можете использовать URLComponents, чтобы избежать необходимости вручную уклониться от строки запроса:
let scheme = "https"
let host = "www.google.com"
let path = "/search"
let queryItem = URLQueryItem(name: "q", value: "Formula One")
var urlComponents = URLComponents()
urlComponents.scheme = scheme
urlComponents.host = host
urlComponents.path = path
urlComponents.queryItems = [queryItem]
if let url = urlComponents.url {
print(url) // "https://www.google.com/search?q=Formula%20One"
}
extension URLComponents {
init(scheme: String, host: String, path: String, queryItems: [URLQueryItem]) {
self.init()
self.scheme = scheme
self.host = host
self.path = path
self.queryItems = queryItems
}
}
if let url = URLComponents(scheme: "https",
host: "www.google.com",
path: "/search",
queryItems: [URLQueryItem(name: "q", value: "Formula One")]).url {
print(url) // https://www.google.com/search?q=Formula%20One
}