-1

I have been having some issues with my prepareForSegue call. Whenever I try to segue to the next view controller. It gets an error and crashes at the point where I am passing the tripLikes to the next view controller.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "toDetailScene") {


        //Hooking up places-holder values
        let viewController = segue.destinationViewController as! DetailViewController

        let cell = sender as! CustomPFTableViewCell


        viewController.tripName = cell.nameTextLabel.text!
        viewController.tripAuthor = cell.authorTextLabel.text!
        viewController.tripLikes = Int(cell.numLikes.text!)!
        viewController.tripDescrip = cell.descriptionHolder

    }
}

Each of the values that we are passing to are values in the destination view controller.

JAL
  • 41,701
  • 23
  • 172
  • 300
  • what is the fail reason ? – Teja Nandamuri Mar 22 '16 at 15:34
  • 3
    You will be in a world of pain until the moment you stop using force-unwrapping. The day you don't see `xxx!` anymore in your code will be the day of enlightenment. Seriously. Use `if let` or anything equivalent. – Eric Aya Mar 22 '16 at 15:36
  • whats the value of cell.numLikes.text! ? – Ulysses Mar 22 '16 at 15:36
  • @EricD. Using forced unwrapping with `sender` is actually better than using `if let`. What would you put into `else`? An assert? – Sulthan Mar 22 '16 at 15:42
  • See this thread I wrote on the subject of optionals and force-unwrapping: http://stackoverflow.com/questions/35683813/im-getting-an-error-fatal-error-unexpectedly-found-nil-while-unwrapping-an-op – Duncan C Mar 22 '16 at 16:28

1 Answers1

10

You're doing a lot of force-unwrapping with Int(cell.numLikes.text!)!. If any of those values are nil, your program will crash.

Why not try something safer, such as an if-let flow:

if let text = cell.numLikes.text {
    if let textInt = Int(text) {
        viewController.tripLikes = textInt
    } else { // Int cannot be constructed from input
        viewController.tripLikes = 0
    }
} else { // cell.numLikes.text was nil
    viewController.tripLikes = 0
}
JAL
  • 41,701
  • 23
  • 172
  • 300