Swift - Error: Zero unexpectedly found while expanding optional value

I am making an application in Swift, but I still get an error in the TableViewController class. I could not find a way to fix this and kept getting this error:

override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell : TextTableViewCell = tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath : indexPath!) as TextTableViewCell let madan : PFObject = self.timeLineData.objectAtIndex(indexPath!.row) as PFObject cell.timestampLabel.alpha = 0 cell.usernameLabel.alpha = 0 cell.madanTextView.alpha = 0 cell.madanTextView.text = madan.objectForKey("content") as String var dateFormatter : NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy HH:mm" cell.timestampLabel.text = dateFormatter.stringFromDate(madan.createdAt) var findSender : PFQuery = PFUser.query() findSender.whereKey("objectId", equalTo: madan.objectForKey("sender").objectId) var i = 1 findSender.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in if !error { let user : PFUser = (objects as NSArray).lastObject as PFUser // Error here cell.usernameLabel.text = user.username UIView.animateWithDuration(0.5, animations: { cell.timestampLabel.alpha = 1 cell.usernameLabel.alpha = 1 cell.madanTextView.alpha = 1 }) } } return cell } 

I cannot find a way to fix this.

+2
source share
2 answers

It looks like objects returning as nil . First check for zero:

 if !error { if let actualObjects = objects { let possibleUser = (actualObjects as NSArray).lastObject as? PFUser if let user = possibleUser { cell.usernameLabel.text = user.username // ... } } } 

Note. Have I changed your as to as? . lastObject already returns an optional parameter, so you can also continue execution if the last object cannot be converted to PFUser. Also, since lastObject can return zero, you also need to check that for nil .

+2
source

To avoid this error, you need to make sure that one importing thing when declaring an object:

 var isActive: Bool? 

? is important to add, so now you can check for nil values โ€‹โ€‹whenever you are by accessing this variable called isActive , as shown below:

  • if isActive == nil
  • if let _isActive = isActive as Bool?

So Optional values โ€‹โ€‹should be declared using ? .

0
source

Source: https://habr.com/ru/post/974551/


All Articles