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?

AL.
  • 36,815
  • 10
  • 142
  • 281
MarksCode
  • 8,074
  • 15
  • 64
  • 133

2 Answers2

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)

        }
    })
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • FYI - I strongly urge you to spend some quality time reading http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu?s=1|6.4447 – rmaddy Jan 13 '17 at 05:12
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.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105