Swift. Serialization of request parameters

Xcode

The goal

  • In the case of passing parameters to the body of the request, the ability of declaring in the form of a [String: Any] dictionary is required.
let requestParameters = [
"method": "createUser",
"credentials": [
"login": login,
"password": password,
"age": age,
"notificationSettings": [
"notifyNews": isNotifyNews,
"notifyCabinet": isCabinetNotify
]
]
]
struct LoginRequest: Codable {
struct Credentials: Codable {
struct NotificationSettings: Codable {
var notifyNews: Bool
var notifyCabinet: Bool
}

var login: String
var password: String
var age: Int
var notificationSettings: NotificationSettings
}

var method: String
var credentials: Credentials
}
  • In the case of passing parameters as a query string, it is required that the order of elements, set during initialization won't change.
let requestParameters = [
"email": email,
"firstName": firstName,
"age": age
]
email=example@example.com&firstName=Nickey&age=20

The solution

Let’s start serializing the parameters to the body of the request. With the CodingKeyRepresentable protocol introduced in iOS 15.4 and the type erasure technique introduced in Swift 5.6, it’s easier to encode the Any type.

where Key == String

Use

In the first case, when it is required to pass parameters to the body of the request, the method for creating and executing the request will be as follows

Conclusion

Previously, before the advent of CodingKeyRepresentable and type erasure, this solution could also be programmed, only for this it was necessary to additionally create an AnyEncodable container and check the key field for compliance with the String or Int type. However, with the evolution of the platform, it became much more convenient to work with the dictionary, and developer can finally forget about the new trash request model.

  1. CodingKeyRepresentable
  2. Type erasure
  3. URLComponents
  4. URLQueryItem

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store