意外发现零

时间:2018-10-23 11:10:26

标签: swift optional

我想这是基本的Swift,所以我有点尴尬地问:

在我的应用中,我从服务器下载plist文件,如下所示:

 Alamofire.download(url, to: destination).response { response in
       if let url = response.destinationURL {
                    self.holidays = NSDictionary(contentsOf: url)!
                }
            }

该文件是有效文件,已成功下载并实际位于“文档”文件夹中。

但是,该应用程序在

上崩溃了
self.holidays = NSDictionary(contentsOf: url)!

  

致命错误:解开可选值时意外发现nil

有什么作用?

2 个答案:

答案 0 :(得分:1)

您的NSDictionary无法初始化,因此,当您尝试强制打开包装(带有感叹号)时,它会失败并崩溃。

答案 1 :(得分:0)

尝试这样的事情:

if let dictionary = NSDictionary(contentsOf: url) {
    self.holidays = dictionary
}

或者,您可以使用后卫声明:

guard let dictionary = NSDictionary(contentsOf: url) else {
    print("NSDictionary failed to initialise")
    return
}

self.holidays = dictionary
相关问题