Re: Modify JSON in Swift
Re: Modify JSON in Swift
- Subject: Re: Modify JSON in Swift
- From: Quincey Morris <email@hidden>
- Date: Fri, 06 Nov 2015 23:23:04 -0800
- Feedback-id: 167118m:167118agrif8a:167118snjZSiqO9Q:SMTPCORP
On Nov 6, 2015, at 22:54 , Rick Mann <email@hidden> wrote:
>
> if var images = json["images"] as? [[String:AnyObject]]
No, that won’t work because Swift dictionaries have *value* semantics, so you’re *asking* for a copy here. The same thing in Obj-C works because the variable ‘images’ would be a reference.
One possible solution would be to change this:
> if var json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
to this:
> if var json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? NSMutableDictionary
and stick to the realm of NS collection classes, but it’s pretty ugly.
The other issue you have to be careful of is that casting a NSDictionary to (say) ‘[String: AnyObject]’ is probably going to copy the dictionary (to a real Dictionary) anyway, because this is a conversion (i.e. copy) cast, not a pure bridging cast. The only cast (AFAIK) from an object that’s a NSDictionary to Dictionary *without* a conversion is ‘[NSObject: AnyObject]’.
This particular case, of working with Obj-C-derived NSJSONSerialization JSON objects in Swift, is actually really really hard. If the structure of the JSON object is fixed, it’s probably easier to define a Swift struct for it (or rather, a hierarchy of nested structs, dictionaries and arrays), and populate it once at the start and reconstruct the serialization dictionary at the end.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden