解除包装可选值时意外发现nil,即使已为其分配了值 [英] Unexpectedly found nil while unwrapping an Optional value even though it has a value assigned

查看:96
本文介绍了解除包装可选值时意外发现nil,即使已为其分配了值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift从Coronavirus API获取JSON.但是,当我尝试运行代码时,出现此错误.

I am using Swift to get a JSON from a Coronavirus API. However when I try to run the code I get this error.

致命错误:解开一个可选值时意外发现nil:第22行

Fatal error: Unexpectedly found nil while unwrapping an Optional value: line 22

我的代码的一部分是

override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = "https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure={%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22}"
        getData(from: url)
        // Do any additional setup after loading the view.
    }
    
    private func getData(from url: String) {
        
        let getfromurl = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
            guard let data = data, error == nil else{
                print("Something Went Wrong")
                return
            }
            
            //Have data
            var result: Response?
            do {
                result = try JSONDecoder().decode(Response.self, from: data)
            }
            catch{
                print("failed to convert \(error.localizedDescription)")
            }
            
            guard let json = result else {
                return
            }
            
            print(json.data.date)
        })
        getfromurl.resume()
    
    }

第22行是:

let getfromurl = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in

我很困惑,因为我认为这意味着url没有分配任何东西,但是即使调试器也认为它有作用.

I am confused because I think that it means that url has nothing assigned to it, but even the debugger thinks it does.

更新:

我可以获取数据,但是一旦获取错误.错误是:

I can get the data but I get an error once I get it. The error is:

无法转换valueNotFound(Swift.Int,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:"data"; intValue:nil),_JSONKey(stringValue:"Index 0&",intValue:0), CodingKeys(stringValue:"newDeathsByDeathDate",intValue:nil)],debugDescription:"Exped Int value but found null.",underlyingError:nil))

failed to convert valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "newDeathsByDeathDate", intValue: nil)], debugDescription: "Expected Int value but found null instead.", underlyingError: nil))

转换失败表明解码JSON和值时出错.

The failed to convert shows it is an error in decoding the JSON and the values.

推荐答案

该异常并不表示urlnil,而是URL(string:url)nil

The exception does not mean that url is nil, but URL(string:url) is nil

您需要检查url字符串是否为有效的网址:

You need to check if the url string is a valid url:

private func getData(from url: String) {
    guard let theURL = URL(string: url) else { print ("oops"); return }
    let getfromurl = URLSession.shared.dataTask(with: theURL, completionHandler: {data, response, error in
       /* ... */
    }
}

更新

因为现在给出了url字符串:问题是花括号;它们在 RFC1738 中标记为不安全替换为%7b(打开)和%7d(关闭),因此:

Update

Since the url string is now given: The problem are the curly braces; they are marked as unsafe in RFC1738 and should be replaced by %7b (opening) and %7d (closing), hence:

let url = "https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7b%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22%7d"

let theUrl = URL(string: url)
print (theUrl)

这也是官方API文档中的示例:

This is also an example in the official API documentation:

curl -si 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7B%22name%22:%22areaName%22%7D'

这篇关于解除包装可选值时意外发现nil,即使已为其分配了值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆