Reputation: 700
To perform a POST request with Alamofire, I would like to create a Json dictionary with an array (with elements of type AnyObject) as a dictionary value.
However, when I define the dictionary as [String: AnyObject]
and try to save an array it results in a SwiftDeferredNSArray
.
var fields = [String: AnyObject]()
fields["key1"] = [1,2,3] // But this could also be an array of type Array<AnyObject>
fields["key2"] = "Foo"
print(fields)
Output: "["key1": <_TtCs21_SwiftDeferredNSArray 0x7fdfe9f0c2d0>(\n1,\n2,\n3\n)\n, "key2": Foo]\n"
When the dictionary values are defined of type Any
the output is what I expect to be:
var fields = [String: Any]()
fields["key1"] = [1,2,3]
fields["key2"] = "Foo"
print(fields)
Output: "["key1": [1, 2, 3], "key2": "Foo"]\n"
Unfortunately, Alamofire seems not to accept dictionary values of type Any
:
Cannot convert value of type '[String : Any]?' to expected argument type '[String : AnyObject]?'
How should I use Alamofire with POST requests with Swift arrays?
Upvotes: 1
Views: 536
Reputation: 1
I too faced the same problem in Swift 2.2
I tried to convert the dictionary of type [String: AnyObject] to a dictionary of [NSObject: AnyObject] and then while passing the value to Alamofire converted the dictionary back to [String: AnyObject]. This worked for me. Try this solution.
Edit:
To answer your question, try
var fields = [NSObject: AnyObject]()
Upvotes: 0
Reputation: 700
Although I don't know whether the SwiftDeferredNSArray
output is a bug in Swift, in Swift 3 the dictionary value must be Any
by default.
Since this is also updated in the Swift 3 version of Alamofire, the SwiftDeferredNSArray
does not occur anymore and the problem is solved.
Upvotes: 1