Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Weather App with Swift (Retired) Concurrency Using Our JSON Data

Paul Yorde
Paul Yorde
10,497 Points

How to access the array elements of the NSDictionary?

The video demonstrates how to access the object keys, and I get that. However, there is data that I would like to access that hasn't been demonstrated. For example, how do I access the data array ( I assume this an array)?

{
currently = {
   icon = "clear-day";
};

daily = {
     data = (
              {
      apparentTemperatureMax = "66.02";

      }
   );
}

}

1 Answer

Jason Wayne
Jason Wayne
11,688 Points

From what I experienced, it depends whether it's Objective-C or Swift. Because Swift has Array type which can also be bridged to NSArray. And usually the Array returned type is optional, which we would have to unwrap it with the ! symbol.

In objective-C, you could just use the dictionary's method called, valueForKeyPath. For instance, [theDictionary valueForKeyPath: @"daily.data.apparentTemperatureMax"]; That would get you the value of apparentTemperatureMax.

In Swift, I had tried this, but I got thrown off when there is an array within the dictionary. My suspect is because we have to unwrap at the Array level, in order to proceed. The way I approached it was going through each level when there is an Array. For instance:

var theArray: NSArray() theArray = theDictionary.valueForKeyPath("daily.data") as? NSArray

var theDictionaryInTheArray = NSDictionary() var apparentTemperatureMax = NSString()

for theDictionaryInTheArray in self.theArray! { self.apparentTemperatureMax = theDictionaryInTheArray.valueForKeyPath("apparentTemperatureMax") as? NSString }

Basically in Swift, I use valueForKeyPath to get what I need in the dictionary, as the array needs to be unwrap in order to proceed. On the other hand, in Objective-C, you could use valueForKeyPath all the way.

Hope this helps. =]

If you do find a way to use valueForKeyPath all the way in Swift, please do share. =]

Paul Yorde
Paul Yorde
10,497 Points

That looks promising, thanks!