swift中URLQueryItem的作用是什么?

Agu*_*ana 0 ios swift

我是 iOS 开发的初学者,最近我正在学习在 iOS 开发中使用 rest API 进行网络连接。在构造 URL 以发出请求时,我发现了这样的代码:

var queryComponents: [URLQueryItem] {
    var components = [URLQueryItem]()

    for (key, value) in parameters {
        let queryItem = URLQueryItem(name: key, value: "\(value)")
        components.append(queryItem)
    }

    return components
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么数组组件应该是 URLQueryItem 数据类型。

提前致谢 :)

Bha*_*ath 5

实际上在URLComponents有一个称为属性queryItems需要的阵列URLQueryItem,其目的是增加在API请求的参数数

在您的情况下,为什么他们将 queryComponents 实现为数组是因为他们会为 queryComponents 中的请求分配多个 URLQueryItems。
例如:

queryComponents.append(NEW_URLQueryItem1)
queryComponents.append(NEW_URLQueryItem2)
Run Code Online (Sandbox Code Playgroud)


最后,当我们访问 queryComponents 时,我们将获得可以直接分配给 URLComponents 的数组值,如下所示,

var urlComponents = URLComponents(string: "API_URL")
urlComponents.queryItems = queryComponents
Run Code Online (Sandbox Code Playgroud)