. Advertisement .
..3..
. Advertisement .
..4..
This is an error message I see in my project: fatal error: unexpectedly found nil while unwrapping an optional value.
Here’s my example code:
let username:String? = “Alice”
let message = “Welcome, ” + username!
print(message)
// Output: Welcome, Alice
I’ve read a few docs but haven’t found the answer yet. Experts please provide a solution to help me deal with this asap. Thanks very much
The cause: When you encounter the fatal error: unexpectedly found nil while unwrapping an optional value, you need to pay attention to that you forced open an optional with
!
while it wasnil
.Let’s assume that this code is capable of running even before the user has signed in. When a user is not logged in, the username field is null. As a result, it is optional.
Solution:
Solve the problem like this:
Before forcing the unwrapping of username, you use
if
-statement to see whether username is null. The code enclosed in the brackets { } is not run when username isnil
.