Fatal error: unexpectedly found nil while expanding optional value, Get json error swift
Get json error
I get an error fatal error: unexpectedly found nil while unwrapping an Optional value
when I try to return json
:
func getJson (str:NSString) -> AnyObject{
var proxiesURL = NSURL(string:str)
var proxiesDataJson = NSData.dataWithContentsOfURL(proxiesURL, options: NSDataReadingOptions.DataReadingUncached, error: nil)
var json: AnyObject!
if (proxiesDataJson != nil ){
json = NSJSONSerialization.JSONObjectWithData(proxiesDataJson, options: NSJSONReadingOptions.AllowFragments, error: nil) as AnyObject
}
return json
}
source to share
I guess the question is "What am I doing wrong".
Your function returns AnyObject (optional, so cannot be nil). You have declared json
as AnyObject! (implicitly unwrapping is optional - it could be zero, but you promise the compiler it will have a nonzero value). Yet it json
is zero when trying to return it — either the code on the line was json = NSJSONSerialization.JSONObjectWithData
not executed, or NSJSONSerialization.JSONObjectWithData
nil was returned.
source to share