0

I am a beginner in iOS development, recently I am learning about networking with rest API in iOS development. When constructing URL to make request, I found code like this:

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

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

    return components
}

I don't understand why the array component shall be in URLQueryItem data type.

Thanks in advance :)

Elydasian
  • 2,016
  • 5
  • 23
  • 41
Agung Laksana
  • 781
  • 1
  • 12
  • 26

1 Answers1

5

Actually in URLComponents has a property called queryItems which requires array of URLQueryItem, Its purpose is to add number of parameters in the API request

In your case why they would have implemented queryComponents as an array is that they would have been assigning multiple URLQueryItems for a request in queryComponents.
Eg:

queryComponents.append(NEW_URLQueryItem1)
queryComponents.append(NEW_URLQueryItem2)


And finally when we access queryComponents we will get array value which we can directly assign to URLComponents as follows,

var urlComponents = URLComponents(string: "API_URL")
urlComponents.queryItems = queryComponents
Bharath
  • 2,064
  • 1
  • 14
  • 39