1

I'm trying to read from the database and place the values into an array of strings. However, when I try to push the values into an array then print the array the app crashes.

var pets: [String]?

override func viewDidLoad() {
    super.viewDidLoad()

    let userRef = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("pets")
    userRef.observeSingleEvent(of: .value, with: { snapshot in
        if let snap = snapshot.value as? Bool {
            print("no values")
        } else if let snap = snapshot.value as? NSDictionary {
            for value in snap {
                print(value.key as! String)    // Prints out data in the database
                self.pets?.append(value.key as! String)
            }
            print(self.pets!)

        }
    })

Does anybody know why the print(value.key as! String) prints out the data but then when I print out the array the app crashes with unexpectedly found nil while unwrapping an Optional value?

0

2 Answers 2

1

You never initialize pets. You declare it as an optional but never assign it a value. Why not change your code to the following:

var pets = [String]() // start with an empty array 

override func viewDidLoad() {
    super.viewDidLoad()

    let userRef = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("pets")
    userRef.observeSingleEvent(of: .value, with: { snapshot in
        if let snap = snapshot.value as? Bool {
            print("no values")
        } else if let snap = snapshot.value as? NSDictionary {
            for value in snap {
                print(value.key as! String)    // Prints out data in the database
                self.pets.append(value.key as! String)
            }
            print(self.pets)

        }
    })
Sign up to request clarification or add additional context in comments.

1 Comment

FYI - I strongly urge you to spend some quality time reading stackoverflow.com/questions/32170456/…
1

Your array is nil when you try to force-unwrapping using:

print(self.pets!)

As you are using self.pets?.append() you don't have any problem because you are using the chaining of optionals, but your array, in fact, is nil at that time because you forgot to initialize it before use it. If you instead use self.pets!.append() you will see a runtime error instead.

So as @rmaddy suggest you can initialize the array at the beginning or just inside your viewDidLoad() it's up to you.

I hope this help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.