Lenx van Zyl Lenx van Zyl - 1 month ago 6
Swift Question

Could not cast value of type 'Swift.Dictionary<Swift.String, protocol<>>' to 'Swift.AnyObject'

I am trying to cast my

[String : Any]
to a JSON Format before sending it to an API.

var orderRequestUserValues : [String : Any] = [ "ClientID": "\(clientID)",
"UserName": "\(userName)",
"Password": "\(password)",
"ModuleID": "StockProcessing",
"FunctionID": "SetStockOrder",
"TransmissionFlags": 32,
"TransmissionMethod": 5


]

var requestParameters : [String : Any] = [ "ActivityType": 2,
"ActivityReference1": "",
"ActivityReference2": "",
"Notes": "",
"ProcessingUserUnique": 1
]

requestParameters.updateValue(usedObjectDictionaries, forKey: "ListofStockActivityData")


orderRequestUserValues.updateValue(requestParameters, forKey: "RequestParameters")


But because my method of casting expects a
AnyObject
I try and force cast it, but I receive an error:


Could not cast value of type 'Swift.Dictionary>' to 'Swift.AnyObject'.


do{

let newDict = try NSJSONSerialization.dataWithJSONObject(orderRequestUserValues as! AnyObject, options: NSJSONWritingOptions.PrettyPrinted) // Inflicts an error

let decoded = try NSJSONSerialization.JSONObjectWithData(newDict, options: [])


Must I use another method of casting to JSON format, or what would be my best alternative.

Answer

You are working with Swift 2 and the problem you have is about Any not convertible to AnyObject. Down casting from Any to AnyObject is not possible. So declare your dictionary as [String: AnyObject] instead of [String: Any].

var orderRequestUserValues : [String : AnyObject]   = [ "ClientID": "\(clientID)",
                                                   "UserName": "\(userName)",
                                                   "Password": "\(password)",
                                                   "ModuleID": "StockProcessing",
                                                   "FunctionID": "SetStockOrder",
                                                   "TransmissionFlags": 32,
                                                   "TransmissionMethod": 5]