2

I'm trying to send data from my first ViewController to my second One.

It works fine with a simple Int but with this Double it doesn't work and I don't understand why. So if you can explain why it doesn't work it's cool !

My declaration in first ViewController :

var time: Double? = 0.00

Then I try to send it to my other ViewController:

let vc = segue.destination as! MySecondViewController
   vc.rows = rows[pathForAVC]
   vc.lap = lap[pathForAVC]
   vc.indexPath = pathForAVC
   vc.time = rows[pathForAVC]["Time"]! as! Double

fatal error: unexpectedly found nil while unwrapping an Optional value

And my second ViewController:

var time: Double? = 0.00
topLabel.text = "\(time!)"

N.B:

rows is a Dictionnary:

var rows: [[String : AnyObject]] = [[:]]

I really don't understand my mistake...

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
pierreafranck
  • 445
  • 5
  • 19
  • 2
    This doesn't have anything to do with passing your value... to me it looks like `rows[pathForAVC]["Time"]` doesn't seem to contain a value and you are force unwrapping it. Try safely unwrapping it using `if let unwrappedTime = rows[pathForAVC]["Time"] as? Double {}` – Dan Beaulieu Jul 21 '17 at 13:18
  • 1
    There are too much force unwrapping going on there. You should really avoid using it. Ever. – Desdenova Jul 21 '17 at 13:22
  • Additionally if you intend to store `Double`s in your dictionary then its type should really be `[[String : Any]]`. `Double` conforms to `Any` not `AnyObject`. – Slayter Jul 21 '17 at 13:31

1 Answers1

3

The problem is that you are force unwrapping a value that may not be there:

vc.time = rows[pathForAVC]["Time"]! as! Double

If rows[pathForAVC]["Time"]! is nil, your application will crash. You should really avoid using ! unless your application simply cannot continue operating without that value. And those situations should be rare.

You should instead safely unwrap your value using an if let statement like this:

if let unwrappedTime = rows[pathForAVC]["Time"] as? Double {
    print(unwrappedTime)
}

(I'm not near Xcode right now but the above code should be close enough to get valuable hints from the compiler).

Let me know if you need any more clarification.

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135