致命错误:在展开Optional值时意外发现nil,获取json错误swift

小弟调*_*弟调调 3 macos cocoa json objective-c swift

在此输入图像描述

得到json错误

fatal error: unexpectedly found nil while unwrapping an Optional value当我尝试返回时,我收到错误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
}
Run Code Online (Sandbox Code Playgroud)

Kre*_*iri 6

我认为问题是"我做错了什么".

您的函数返回AnyObject(非可选,因此不能为零).你声明json为AnyObject!(隐式解包可选 - 它可能是零,但你保证编译器它将具有非零值).但是json当你试图返回时它是零 - 在线上的代码json = NSJSONSerialization.JSONObjectWithData没有被执行,或者NSJSONSerialization.JSONObjectWithData返回为零.