penatheboss penatheboss - 1 year ago 76
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")
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
log in 4.1
, but not 4.2. The error must be occurring on the line in between. I check that
isn't nil, but it still prints nil. How can I resolve this? Thanks!

Answer Source

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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download