-1

enter image description here

The optional Bool paid is nil. It gets assigned a value. The value is printed. Next line of code i have an else if. The value is nil. Question: how and why?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Salazar
  • 11
  • 1
    Copy/paste code, it's better. WHat's the output of the logs? If you have multiple document, it'd be the last value only (since it's override)? – Larme May 19 '21 at 10:46
  • As mentioned already, you need to post your code, not an image. That being said, it looks to me like you're not printing `paid`, you're printing `dict["paid"]`. – West1 May 19 '21 at 10:58
  • You need to [edit] your question to include all relevant code as text, using proper code formatting - and not as a screenshot -, in the form of a [mcve] in order to make the question on-topic. – Dávid Pásztor May 19 '21 at 11:10
  • *The optional Bool paid is nil. It gets assigned a value* - no, it doesn't. You would need a nil coalescing operator for that - `paid = dict["paid"] as? Bool ?? true`. However since that's in a loop it will be assigned over and over by the loop and will always be whatever the last iteration of the loop sets it to. Also force-unwrapping an optional is often unwise, so this `paid!` is telling your code that you guarantee it will not be nil, but as you can see, it can with your code. – Jay May 19 '21 at 17:55

2 Answers2

0

It seems the value is being accessed before it's ready. You'll need to unwrap it to be sure it's assigned before use.

try this:

guard let safePaid = paid else { return } 
Josh
  • 225
  • 2
  • 14
0

You're printing dict["paid"] instead of paid. If you print paid, you'll probably see that it's nil.

West1
  • 1,430
  • 16
  • 27