Other answers suggest you deploy an optional option, but the real problem is that you force the option to deploy using ! despite the fact that she is nil .
When you write something! , you say: " something may be nil , but if so, I want my program to crash."
The reason nil can be returned is if the result is invalid - for example, if you are trying to extract a key from a dictionary that is not there, or if the URL does not indicate a valid image to load.
You can combine the check for nil with an if , which expands the optional parameter and returns an optional value until the value was nil . You can also combine them together, so if you need to expand the value and then pass it into a call that also returns optional, you can do it all in one if :
if let httpUrl = subJson["image_url"].string, url = NSURL(string: httpUrl), data = NSData(contentsOfURL: url), image = UIImage(data: data) {
Note: in the first line, calling .string , not .stringValue - .string also returns an optional parameter with nil if the value is not present.
Of course, combining all of these deployments means that you cannot say which one was unsuccessful, so you can break them down into separate statements.
source share