Convert Dictionary<String: Any?> to NSData

john tully picture john tully · Feb 26, 2016 · Viewed 7.2k times · Source

I am using the swift form class Eureka to to build my form. On button submit I get my fields using form.values(). This gives me the following

let formvalues = form.values()

print(formvalues)

["field1":Optional(20), "field2": Optional("")]

I am trying to post the field names/values

Answer

Duncan C picture Duncan C · Feb 26, 2016

There is no guaranteed way to serialize a dictionary containing Any type values in it. Any can be any swift construct, including objects, structs, tuples, etc. There is no one-size-fits-all serialization that supports serializing any data type like that.

Now if you have a dictionary of type <String: String>, <String: Int>, or other fixed types, then you could use NSJSONSerialization to export it as JSON. You just need to stick to the types defined by JSON. You could also export it as XML or a plist file.