Search code examples
iosjsonswiftdictionaryalamofire

How to use Alamofire with an array in a Json dictionary?


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?


Solution

  • 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.