ios


How to recursively traverse NSDictionary in swift


I am writing an app, and one of the features I need to implement requires the app to pull JSON data from a website, store it in a dictionary, then be able to use all of the keys and display the values. I will not know what the structure of the dictionary will look like, so I was hoping to recursively traverse the dictionary to retrieve all of the information.
I have the the JSON stored in a dictionary from the website that I need, and when I put the dictionary variable in a println() statement it displays correctly.
I found this link and I think this, or some variation of this should work, but I am still fairly new to swift and I am not sure how this translates from Objective-c to swift.
The part of that link that I am interested in is this:
(void)enumerateJSONToFindKeys:(id)object forKeyNamed:(NSString *)keyName
{
if ([object isKindOfClass:[NSDictionary class]])
{
// If it's a dictionary, enumerate it and pass in each key value to check
[object enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
[self enumerateJSONToFindKeys:value forKeyNamed:key];
}];
}
else if ([object isKindOfClass:[NSArray class]])
{
// If it's an array, pass in the objects of the array to check
[object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self enumerateJSONToFindKeys:obj forKeyNamed:nil];
}];
}
else
{
// If we got here (i.e. it's not a dictionary or array) so its a key/value that we needed
NSLog(#"We found key %# with value %#", keyName, object);
}
}
I'm not sure how to go about this, any help or pointers in the right direction are appreciate. Thanks!
EDIT: This is the direction I started to go in, but there were a lot of errors. I tried to fix them but didn't have much luck.
func enumerateJSONToFindKeys(id:AnyObject, keyName:NSString){
if id.isKindOfClass(NSDictionary)
{
AnyObject.enumerateKeysAndObjectsUsingBlock(id.key, id.value, stop:Bool())
{
self.enumerateJSONToFindKeys(id.value, forKeyNamed: keyName)
}
}
else if id.isKindOfClass(NSArray)
{
}
}
Try this:
func enumerateJSONToFindKeys(object:AnyObject, forKeyNamed named:String?) {
if let dict = object as? NSDictionary {
for (key, value) in dict {
enumerateJSONToFindKeys(value, forKeyNamed: key as? String)
}
}
else if let array = object as? NSArray {
for value in array {
enumerateJSONToFindKeys(value, forKeyNamed: nil)
}
}
else {
println("found key \(named) value \(object)")
}
}
It uses the Swift as? conditional casting operator as well as native iteration over both the NSDictionary and NSArray.

Related Links

Touch ID Passcode Integration in iOS
how to get today's date less 18 years
iOS Not able to change the frame of UITextField inputAccessoryView.superview
Publishing issue, Callkit is included even we are not using it
How to get crash information from a TestFlight launched app?
Parse: Updating relation on user in Local Datastore
iOS 10, Local notification show when app is in forground?
What is the reason for this UITableView not showing up on my view controller?
Xcode inserted fileprivate functions after updating to Swift 3 [duplicate]
Xamarin ios UItableView Empty rows at top using Task Scheduler in background
How to test iOS app's localization on a real device when using appium?
How to prevent NSInternalInconsistencyException with Realm and UICollectionView
(Swift, EarlGrey) move slider to the middle
How can I make physicBody dynamic only on needed levels?
check if item exists in core data EFFICIENTLY
How to continue in the background a connection started with NSURLConnection in the foreground?

Categories

HOME
codeigniter
dom
robotframework
appium-ios
path
image-segmentation
feed
xquery
logback
spi
wikipedia-api
oracle-adf
cross-domain
predictionio
socrata
range
zipfile
intl
hadoop2
obiee
frequency
nservicebus
numericupdown
orchardcms-1.10
zap
swig
textmatebundles
hp-alm
accelerated-mobile-page
angular-services
parallax
listbox
fat-free-framework
stl
toastr
vue-router
pvlib
background-process
advanced-installer
jupyter-irkernel
response
weebly
amazon-elasticsearch
protobuf-3
xargs
botkit
pulseaudio
kendo-chart
name-mangling
vega-lite
formstack
canopen
unityscript
catalina
mapr
manifoldcf
logstash-jdbc
olingo
ocsp
xnamespace
namenode
selenium2library
isapi-rewrite
webpack-hmr
groupbox
xelement
parsoid
sqlj
linqtocsv
uikeyboard
cng
push-api
double-quotes
maven-cargo
sketching
omap
genexus-gam
twitter-follow
swift-array
modern-ui
office-2010
iqueryable
monk
globus-toolkit
spread-toolkit
tinkerpop-frames
populate
declspec
micro-orm
programmers-notepad
memoization
neventstore
northwind
memento
timespan
guvnor
msxsl
azure-role-environment
exact-synergy-enterprise
springboard
having
chickenfoot
newsgroup

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App