I have a problem with the data i get from the Firebase Database.
I´m getting the correct data from the database and i can directly print them out, but i can´t save the data on a variable or save the data in a structure.
Here is my code:
class viewController: UIViewController {
var ref: DatabaseReference!
var handle: DatabaseHandle!
struct person {
var name: String
var ids: [String]
}
var personArray: [person] = []
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.databse().reference()
handle = ref.child("path").observe(.childAdded, with: { (snapshot) in
if let nameDatabase = snapshot.value as? String {
print(nameDatabase) //works
self.personArray.append(person(name: nameDatabase, ids: ["123"]))
}
})
print(personArray[0].name) //Error, array is empty
}
}I get the error: Fatal error: Index out of range.
But i have now idea, why the array is empty?!
If i save the data on a viriable and print it out in the if statement it works, but if I print it outsite the handle-function the variable is empty again.