swift2guard-statement

Swift 2 optional guard on string


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.


Solution

  • 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