Results
public struct Results
It contains results related to a web request.
-
The returned data by the server.
Declaration
Swift
private(set) public var data: Data?
-
A
GTRest.Response
object which contains server response data. -
An error object describing potential errors.
Declaration
Swift
private(set) public var error: Error?
-
A convenient method to convert raw fetched data to a custom type by decoding it using JSONDecoder.
Important
Custom type must conform to Decodable or Codable protocol.JSONDecoder object used to decode data in this method can be configured in the
decoderConfiguration
handler. Keep it nil in case you don’t want to make any configuration to JSONDecoder instance.In case decoding fails an exception is thrown by the method.
Example:
Consider the following struct:
struct User: Codable { var id: Int? var firstName: String? var lastName: String? }
Also, the following server fetched data:
{ "id": 325, "first_name": "Gabriel", "last_name": "Theodoropoulos" }
Here’s how to convert fetched user data, using the
decoderConfiguration
to set theconvertFromSnakeCase
as thekeyDecodingStrategy
:let rest = GTRest() let url = URL(...) // Additional configuration... rest.makeRequest(toURL: url, withHttpMethod: .get) { (results) in do { if let user = try results.convertData(toType: User.self, decoderConfiguration: { (decoder) in decoder.keyDecodingStrategy = .convertFromSnakeCase }) { // User data has been successfully converted into a `User` object. print(user) } } catch { print(error.localizedDescription) } }
Declaration
Swift
public func convertData<T>(toType type: T.Type, decoderConfiguration config: ((_ decoder: inout JSONDecoder) -> Void)?) throws -> T? where T : Decodable
Parameters
type
The custom type to convert
data
to.decoderConfiguration
Use this closure to perform any configuration to the JSONDecoder instance that is used in this method to decode the data. Set
nil
if no configuration needed.decoder
The JSONDecoder instance used to decode fetched data.
Return Value
An object of the custom type specified, or
nil
if no data exists or decoding fails.