I'm declaring a TargetType extension. I'm providing parameters for all the items in the enum, but for one of the items, I need the parameters to be return as an array, not a dictionary.
This might explain better:
swift
var parameters: [String: Any]? {
switch self {
case .doSomething(let ArrayOfStrings):
return ArrayOfStrings
}
}
I'm using JSONEncoding and I need to be able to return an array.
Hello I am not sure I am understanding your question completely but are you asking how to convert a dictionary to an array?
If so, for example:
let dictionary = [ "a" : "hello", "b": "how are you"]
let arrayOfValues = Array( dictionary.values.map { $0 })
That should work.
If I misunderstood can you please clarify? Maybe with an example of your data?
@gmoalvarez No, I need to return an array, but the variable will only let me return a dictionary object. For example, look at the input that the GitHub API needs: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue
But those are not parameters, right? That's just the URL.
@BasThomas Well, if I use JSONEncoding for ParameterEncoding, wouldn't the parameters be sent as JSON? Maybe, I'm incorrect.
O I think I understand. You will need to modify the request then. Looking at the example in the Moya docs for Request Mapping:
https://github.com/Moya/Moya/blob/master/docs/Endpoints.md#request-mapping
let requestClosure = { (endpoint: Endpoint<GitHub>, done: MoyaProvider.RequestResultClosure) in
var request = endpoint.urlRequest
// Modify the request however you like.
request.httpBody = Array( endpoint.parameters.values.map { $0 }) //convert to array here!
done(.success(request))
}
let provider = MoyaProvider<GitHub>(requestClosure: requestClosure)
@gmoalvarez Awesome, but just to make sure, if I'm just using dictionary objects rather than an array, can I use JSONEncoding?
I think you can use JSONEncoding for your parameters in that case, yep!
If not, you can follow this tutorial:
https://github.com/Moya/Moya/blob/master/docs/Examples/ArrayAsRootContainer.md
I haven't used array as a root container before but it sounds straightforward since you are customizing the request anyway.
Most helpful comment
O I think I understand. You will need to modify the request then. Looking at the example in the Moya docs for Request Mapping:
https://github.com/Moya/Moya/blob/master/docs/Endpoints.md#request-mapping