0

I am writing a function that allows me to read the data inside the Database. I can read the String from Firebase but I cannot read the arrays. I tried like this but it doesn't work:

func fetchData(collection: String) { 
    DatabaseFirestore.collection(collection).addSnapshotListener { (querySnapshot, error) in 
        guard let documents = querySnapshot?.documents else {
            print("No documents") 
            return
        }
        self.example = documents.map { (queryDocumentSnapshot) -> Example in
            let data = queryDocumentSnapshot.data()
            let ex1 = data["ex1"] as? String ?? "" // it is not an array in the database
            let ex2 = data["ex2"] as? String ?? "" // is an array in the database
            return Example(ex1: ex1, ex2: ex2)
        }
    }
} 

How could I change this line so that it reads the array inside the database?

let ex2 = data["ex2"] as? String ?? ""
3
  • 1
    as? [Any] instead of as? String? But it's unclear what you need exactly since you are mixing Array & String. Commented Aug 2, 2022 at 19:02
  • ex1 is a String, ex2 is an array of strings within the database. I'm looking for a way to save it in variables. Commented Aug 2, 2022 at 19:05
  • if you cannot understand the difference between a String and an array of String, [String], then it's time to read the basics again at: docs.swift.org/swift-book/LanguageGuide/TheBasics.html Commented Aug 2, 2022 at 23:34

1 Answer 1

0

Casting as [String] instead of String might fix the issue


You also could check this answer - it could be helpful when retrieving arrays and dictionaries from Firebase

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

2 Comments

If I write " let ex2 = data["ex2"] as? [String] ?? "" " gives this error: Cannot convert value of type 'String' to expected argument type '[String]'. I tried to change it to this: " let ex2 = data["ex2"] as? [String] ?? [ ] ", and when I return the value I write: " return Example(ex1: ex1, ex2: ex2 as Any as! [String]) ". If in the database there are no values ​​related to "ex2", and I try to print the value the app crashes. How can you make sure that if it finds no "ex2" value, it takes an empty string as a value? I also tried this: let ex2 = data["ex2"] as? [String] ?? [ ""]
With let ex2 = data["ex2"] as? [String] ?? [], use Example(ex1: ex1, ex2: ex2). Read the basics again, it will tell you, doing this: Example(ex1: ex1, ex2: ex2 as Any as! [String]) is crazy.

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.