简体   繁体   中英

Xcode says found nil, but actual value is not nil

I am trying to get a value from Firebase Firestore, but for some reason, xcode says that it found nil while unwrapping an optional. I put a check in place to display something else if it is nil, but it still goes in my if , and I am not sure why.

Here is my code:

        let db = Firestore.firestore()
        let docRef = db.collection("Users").document(Auth.auth().currentUser!.uid)
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                let points = document.data()!["points"]
                print(points)
                if (points != nil) {
                    self.pointsLabel.text = "\(points!)"
                }
                else {
                    self.pointsLabel.text = "There was an error getting your points"
                }
            } else {
                print("Document does not exist")
            }
        }

Any help would be greatly appreciated!

I believe this line:

let points = document.data()!["points"]

is not checked against nil .

What if document.data() is nil ?

Another possibility is your pointsLabel . If you are using IBOutlet for the label and your Firebase callback is called before the view is load, then the error like that may happen.

But you should let us know at which line the error happened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM