Say you have a string of json someText and you want to parse it to a dictionary. Previously I have done this...
let jsonResult: NSDictionary =
try JSONSerialization.jsonObject(
with: someText.data(using: .utf8)!,
options: JSONSerialization.ReadingOptions.mutableContainers)
as! NSDictionary
but that's just a crappy NSDictionary.
It would seem that you can indeed do this......
let jsonResult: [String:Any] =
try JSONSerialization.jsonObject(
with: someText.data(using: .utf8)!,
options: JSONSerialization.ReadingOptions.mutableContainers)
as! [String:Any]
so that's now a real Swift dictionary.
Does this work? Are there drastic efficiency differences, or perhaps other problems?
Confusingly to me,
open class func jsonObject(with data: Data,
options opt: JSONSerialization.ReadingOptions = []) throws -> Any
the call just returns Any anyways. So when you cast it to your [String:Any] or indeed NSDictionary, what's the process, what is best?
Are there drastic efficiency differences
Yes there are.
NSDictionary completely lacks type information, native Swift collection types are much more efficient and highly recommended. And you get mutability for free using var. mutableContainers are useless in Swift anyway.
jsonObject(with data returns Any because the return type can be Dictionary, Array or even String/Number, the least common denominator is Any, cast it to the expected type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With