Fatal error: unexpectedly found nil while expanding optional value, Get json error swift

enter image description here

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
}

      

+3


source to share


2 answers


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.

+6


source


You used! with an optional object that should only be used when you checked it is not null, otherwise it will fail. Should you wrap it up instead? instead!. This is not a glitch and you don't need to check for null.



0


source







All Articles