Divine Davis
Divine Davis

Reputation: 552

Swift unexpectedly found nil while unwrapping an optional value

I can't seem to unwrap this. My objects variable seems to be coming back nil.

//Creating a query
let query = PFUser.query()

query?.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error : NSError?) -> Void in
     self.users.removeAll(keepCapacity : true)       
     for object in objects!
     {
         let user : PFUser = (object as? PFUser)!
         self.users.append(user.username!)
     }
     self.tableView.reloadData()
})

enter image description here

Upvotes: 0

Views: 537

Answers (1)

Midhun MP
Midhun MP

Reputation: 107221

The issue is with the objects : [PFObject]? argument, it is an optional; that means it can be nil. In your code you are trying to forcefully unwrap it for object in objects!. Due to some error you are getting nil objects array and you are trying to forcefully unwrap it, that's the reason for the crash.

You need to change the implementation like:

let query = PFUser.query()
query?.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error : NSError?) -> Void in

  self.users.removeAll(keepCapacity : true)
  if let objects = objects
  {
        for object in objects
        {
           let user : PFUser = (object as? PFUser)!
            self.users.append(user.username!)
        }
   }
   self.tableView.reloadData()
})

Upvotes: 1

Related Questions