penatheboss penatheboss - 4 months ago 12
Swift Question

Unexpectedly found nil after checking for nil

I am trying to save a Firebase username to UserDefault. Here is what I have:

let databaseRef = FIRDatabase.database().reference()
databaseRef.child("Users").child((FIRAuth.auth()?.currentUser?.uid)!).observe(.value, with: { (snapshot) in
print("log in 4")
print(snapshot.value)
if snapshot.value != nil {
print("log in 4.1")
UserDefaults.standard.set(snapshot.value!["username"], forKey: "username")//Crash probably occurs here
print("log in 4.2")
}

})


The system prints
log in 4
and
log in 4.1
, but not 4.2. The error must be occurring on the line in between. I check that
snapshot.value
isn't nil, but it still prints nil. How can I resolve this? Thanks!

Answer

You currently are just checking that snapshot.value contains any value, so is not nil. But that doesn't mean that snapshot.value contains the value "username".

If it is empty initialized, it isn't nil either.

So to check for this specific key you'd have to add a check for the key itself:

if let userValue = snapshot.value?["username"]