0

I'm dealing with an issue in swift 2.0

I get a json file from an API and i'm trying to unwrap some strings out of it.

Sometimes this json gives me a string with the street name of a venue but sometimes not. So when i'm trying this

var street = arrRes[indexPath.row]["venueLocation"]!["street"] as! String 

It always crashes my app saying it is nil. When i comment it my app runs perfect but it doesnt show the street. Any idea of how to unwrap the string without having any issue with nil ??

If tried this code

var street = arrRes[indexPath.row]["venueLocation"]!["street"] as! String 

if street == "" {
   street = "n/a"
}

But it failed also.

David Snabel
  • 9,801
  • 6
  • 21
  • 29
Konstantinos Natsios
  • 2,874
  • 9
  • 39
  • 74

1 Answers1

5

Any time you force unwrap with ! you run the risk of crashing where a value is nil. Instead you can try unwrapping like:

guard let venueDictionary = arrRes[indexPath.row]["venueLocation"] as? [String:AnyObject], let street = venueDictionary["street"] as? String else {
   //You don't have a street string, fail gracefully 
}
print(street)//Now you can use street safely as a string here
Daniel Hall
  • 13,457
  • 4
  • 41
  • 37
  • i have to write `return` inside the `else` ?? – Konstantinos Natsios Jun 02 '16 at 19:42
  • @KwnstantinosNatsios Yes, or `fatalError()` or `break` or something to exit the scope, which is what the `guard` statement does. If you don't want to early exit or use `guard`, then you can change it to: `if let venueDictionary = arrRes[indexPath.row]["venueLocation"] as? [String:AnyObject], let street = venueDictionary["street"] as? String { print(street) //Now you can use street safely as a string here }` – Daniel Hall Jun 02 '16 at 20:08
  • I'm trying to then to send this variable to another View Controller. but at the certain cell that has the `nil` street it doesnt let me go inside the next view controller... but with other cells that have normal street i dont have any issue. – Konstantinos Natsios Jun 02 '16 at 20:13
  • @KwnstantinosNatsios How about something like this: `if let venueDictionary = arrRes[indexPath.row]["venueLocation"] as? [String:AnyObject], let street = venueDictionary["street"] as? String { otherViewController.streetText = street } else { otherViewController.streetText = ""}` – Daniel Hall Jun 02 '16 at 20:18
  • @KwnstantinosNatsios Great! :) – Daniel Hall Jun 02 '16 at 20:19