Satsuki
Satsuki

Reputation: 2196

unexpectedly found nil while unwrapping an Optional value

I am trying to implement a vote up button so that users can vote up a post. Something like a like feature. To do that I use an IB action in the cell view controller like below

@IBAction func vote(sender: AnyObject) {

    if (parseObject != nil) {
        if var votes:Int? = parseObject!.objectForKey("votes") as? Int {
            votes!++

            parseObject!.setObject(votes!, forKey: "votes")
            parseObject!.saveInBackgroundWithTarget(nil, selector: nil)

            votesLabel?.text = "\(votes!) votes"
}

Then I put the below code in the collection view controller if nothing is in the column, the label will show 0.

     if var votes:Int? = parseObject!.objectForKey("votes") as? Int {
        if votes == nil{
            votes = 0}
        cell.votesLabel?.text = "\(votes!) votes" 
    }
    return cell
}

I have no errors in my code, however as soon as I build the app it says unexpectedly found nil while unwrapping an Optional value pointing to the highlighted code. Is my way of implementing this wrong? Thank you.

Upvotes: 1

Views: 122

Answers (2)

iDhaval
iDhaval

Reputation: 3205

Try Below Code:

@IBAction func vote(sender: AnyObject) {
if (parseObject != nil)
{
     if let votes = parseObject!.objectForKey("votes") as? Int {
         parseObject!.setObject(votes + 1, forKey: "votes")
         parseObject!.saveInBackgroundWithTarget(nil, selector: nil)
         votesLabel?.text = "\(votes + 1) votes"
     }
     else
     {
         parseObject!.setObject(1, forKey: "votes")
         parseObject!.saveInBackgroundWithTarget(nil, selector: nil)
         votesLabel?.text = "1 votes"
     }
}

In collection view controller

if (parseObject != nil)
{

   if let votes = parseObject!.objectForKey("votes") as? Int {
       cell.votesLabel?.text = "\(votes) votes"
   }
   else
   {
       cell.votesLabel?.text = "0 votes"
   }
}
return cell

Upvotes: 0

saurabh
saurabh

Reputation: 6775

Instead of forced unwrapping, you can try optional chaining. So the whole expression would return nil instead of throwing error.

if var votes:Int? = parseObject?.objectForKey("votes") as? Int {

EDIT

Its also a better practice to let Swift infer the type of variable, so:

if var votes = parseObject?.objectForKey("votes") as? Int {

Upvotes: 1

Related Questions