如何将字典 [String:String] 转换为 swift 中的 URLQueryItem 5
How to conver dictionary[String:String] to URLQueryItem in swift 5
I have one parameter dictionary
func queryItems(dictionary: [String:Any]) -> URLQueryItem {
var components = URLComponents()
print(components.url!)
components.queryItems = dictionary.map {
URLQueryItem(name: [=11=], value: ( as! URLQueryItem))
}
return (components.url?.absoluteString)!
}
我创建了一个函数,但它不起作用
您的代码没有意义,原因如下:
- return 值是
URLQueryItem
但你 return 一个 String
- 您创建了一个空的
URLComponents
实例,没有方案、主机和路径就毫无意义。
URLQueryItem
的value
不能是URLQueryItem
你能做的就是将字典映射到 URLQueryItem
的数组
func queryItems(dictionary: [String:String]) -> [URLQueryItem] {
return dictionary.map(URLQueryItem.init)
}
或者添加第二个参数并传递 URL
func queryItems(for url: URL, dictionary: [String:String]) -> URL? {
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }
components.queryItems = dictionary.map(URLQueryItem.init)
return components.url
}
I have one parameter dictionary
func queryItems(dictionary: [String:Any]) -> URLQueryItem {
var components = URLComponents()
print(components.url!)
components.queryItems = dictionary.map {
URLQueryItem(name: [=11=], value: ( as! URLQueryItem))
}
return (components.url?.absoluteString)!
}
我创建了一个函数,但它不起作用
您的代码没有意义,原因如下:
- return 值是
URLQueryItem
但你 return 一个String
- 您创建了一个空的
URLComponents
实例,没有方案、主机和路径就毫无意义。 URLQueryItem
的value
不能是URLQueryItem
你能做的就是将字典映射到 URLQueryItem
func queryItems(dictionary: [String:String]) -> [URLQueryItem] {
return dictionary.map(URLQueryItem.init)
}
或者添加第二个参数并传递 URL
func queryItems(for url: URL, dictionary: [String:String]) -> URL? {
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }
components.queryItems = dictionary.map(URLQueryItem.init)
return components.url
}