我有一个程序,我收到一个包含电影列表的 JSON,然后我尝试将这些标题放入一个数组中。代码错误的部分如下:
var movieArray: [JSON]!
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "https://api.themoviedb.org/3/discover/movie", parameters: ["sort_by" : "popularity", "api_key" : "secret"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
let json = JSON(response.result.value!)
//print(json)
let arraySize: Int = json["results"].count
for num in 0...arraySize {
let x = json["results"][num]["title"]
print(x)
self.movieArray[num] = (x)
}
print(self.movieArray[0])
case .Failure(let error):
print(error)
}
}
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
当我运行它时出现这个错误:
Puccini for Beginners
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
谁能解释为什么会这样?
最佳答案
当您尝试解包为 nil 的可选值时会发生此错误。在这种情况下,您的 movieArray 是一个可选值,这意味着它可能具有 nil 值,并且您保证在使用它之前您将具有值,或者您将检查它是否具有值。
要解决它,您可以通过 - 初始化它
var movieArray = [JSON]()
或者检查数组是否为nil
//---- Another way
guard movieArray != nil else {
print("array is nil")
}
// Do stuff with movieAray
声明 self.movieArray[num] = (x)
使用未初始化的 movieArray,因此根本没有元素,所以 num 值可能是什么,因此赋值抛出错误。
BR
关于json - ' fatal error : unexpectedly found nil while unwrapping an Optional value' when reading from JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38156482/