Suleiman Suleiman - 6 months ago 23
JSON Question

'fatal error: unexpectedly found nil while unwrapping an Optional value' when reading from JSON

I have a program where I receive a JSON with a list of movies and I try to put the titles into an array. The erroneous part of the code is the following:

var movieArray: [JSON]!

override func viewDidLoad() {
Alamofire.request(.GET, "", parameters: ["sort_by" : "popularity", "api_key" : "secret"])

.responseJSON { response in
switch response.result {
case .Success:
let json = JSON(response.result.value!)
let arraySize: Int = json["results"].count
for num in 0...arraySize {
let x = json["results"][num]["title"]
self.movieArray[num] = (x)

case .Failure(let error):

self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

When I run it I get this error:

Puccini for Beginners
fatal error: unexpectedly found nil while unwrapping an Optional value

Can anybody explain why this is happening?


This error happens when you try to unwrap optional value which are nil. In this case your movieArray is an optional value which means it may have nil value and you guaranty that before using it you will have values or you will check if it has value.

To solve it you can Initialise it by -

var movieArray = [JSON]()

or check the array for being nil

//---- Another way
guard movieArray != nil else {
    print("array is nil")

// Do stuff with movieAray

The statement self.movieArray[num] = (x) using movieArray which is not initialised and hence no element at all what so ever num value may be and hence the assignment throwing error.