[英]fatal error: unexpectedly found nil while unwrapping an Optional value, Get json error swift
Get json error 得到json错误
I am getting the error fatal error: unexpectedly found nil while unwrapping an Optional value
when I try to return the json
: 我收到错误
fatal error: unexpectedly found nil while unwrapping an Optional value
当我尝试返回json
时fatal error: unexpectedly found nil while unwrapping an Optional value
时fatal error: unexpectedly found nil while unwrapping an Optional value
:
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
}
I assume the question is "what am I doing wrong". 我认为问题是“我做错了什么”。
Your function returns AnyObject (non-optional, thus cannot be nil). 您的函数返回AnyObject(非可选,因此不能为零)。 You declared
json
as AnyObject! 你将
json
声明为AnyObject! (implicitly unwrapped optional - it may be nil, but you promise to compiler that it will have non-nil value). (隐式解包可选 - 它可能是零,但你保证编译器它将具有非零值)。 And yet
json
is nil when you attempt to return it - either code at json = NSJSONSerialization.JSONObjectWithData
line wasn't executed, or NSJSONSerialization.JSONObjectWithData
returned nil. 但是当你试图返回它时
json
是nil - 在json = NSJSONSerialization.JSONObjectWithData
行的代码没有被执行,或者NSJSONSerialization.JSONObjectWithData
返回nil。
You used ! 你用过! with optional object which should be used only when you have checked its not nil, else it will crash.
使用可选对象,只有在检查了它不是nil时才应该使用它,否则它会崩溃。 Instead you should wrap it with ?
相反,你应该用它包装吗? instead of !.
代替 !。 It won't crash and you don't have to check for nil.
它不会崩溃,你不必检查零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.