3

I am using this code to read data from NSDictionary:

let itemsArray: NSArray = response.objectForKey("items") as! NSArray;
let nextPageToken: String = response.objectForKey("nextPageToken") as! String

var videoIdArray: [String] = []

for (item) in itemsArray {
      let videoId: String? = item.valueForKey("id")!.valueForKey("videoId") as? String
      videoIdArray.append(videoId!)
}

But when i items or nextPageToken are not exist i get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Any idea why? how i can fix it?

YosiFZ
  • 7,792
  • 21
  • 114
  • 221

1 Answers1

8

There are two issues in your code:

  1. You are trying to force unwrap an optional that can be nil. Never use forced unwrapping, if you are not sure whether the data will be available or not.
  2. You are using valueForKey: instead of objectForKey: for retrieving data from a dictionary. Use objectForKey: instead of valueForKey: for getting data from a dictionary.

You can fix the crash by:

let itemsArray: NSArray?   = response.objectForKey("items") as? NSArray;
let nextPageToken: String? = response.objectForKey("nextPageToken") as? String

var videoIdArray: [String] = []
if let itemsArray = itemsArray
{
    for (item) in itemsArray
    {
       let videoId: String? = item.objectForKey("id")?.objectForKey("videoId") as? String
       if (videoId != nil)
       {
          videoIdArray.append(videoId!)
       }
     }
}
Community
  • 1
  • 1
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • Hi, i'm using the same code for retrieving object value from a NSDictionary, but it shows an error. Is there any new update in swift 3? – Hilaj S L Jun 18 '16 at 09:31