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?
I have an optional value that is assigned a value, printed succesfully, but when i check it it's nil
Asked
Active
Viewed 47 times
-1
-
1Copy/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 Answers
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
-
-
I don't know what that means. Did you try printing `paid` instead of `dict["paid"]`? That should be the answer to your problem. – West1 May 19 '21 at 13:28