1

How can I convert this object array into a string array? I'm reading records from a firebase collection.

    firebaseDB.collection("message").document(key).collection("messages").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        }
        else {
            self.driverArr.removeAll()
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
                let msgdata = document.data() as! [String:Any]
                var msgObj = Message()
                if let name = msgdata["name"] as? String {
                    msgObj.name = name
                }
                self.driverArr.append(msgObj)
            }
            if self.driverArr.count < 1 {
                print("No Drivers")
            }
            else{
                print("*** Driver Names array ***")
                print(self.driverArr)
            }
        }
    }

The current output of this array is:

[MainApp.Message(name: Optional("Oliver"), userId: Optional(""), msg: Optional(""), creatAt: Optional(0), latitude: Optional(""), longitude: Optional("")), MainApp.Message(name: Optional("Bluesona"), userId: Optional(""), msg: Optional(""), creatAt: Optional(0), latitude: Optional(""), longitude: Optional("")), MainApp.Message(name: Optional("Oliver"), userId: Optional(""), msg: Optional(""), creatAt: Optional(0), latitude: Optional(""), longitude: Optional(""))]

I wish to simply output an array that contains an Array of strings with the names ["Oliver", "Bluesona"...]

1
  • Try this if let name = msgdata["name"] as! String { msgObj.name = name } OR self.driverArr.append(msgObj!) Commented Oct 5, 2018 at 10:08

1 Answer 1

4

You can use compactMap to get all the valid names in the array.

print( driverArr.compactMap({$0.name}) )
Sign up to request clarification or add additional context in comments.

6 Comments

please let me know your answer and this code gives same result? let arrNames = driverArr.map({ (doc: document) -> String in doc.name }) print(arrNames)
No, first thing you are using map which doesn't filter out nil values. Second, driverArray is supposed to be of type Message since you are appending Message objects to it. let arr = driverArr.compactMap { (message) in message.name }
Thanks for reply but i want to confirm that both gives same result right?
Suppose if i have Object array that contains Int, String, Bool values and if i want to get only all int value as array then your .contactMap and .map works as same?
Okay, Thanks for your guide.
|

Your Answer

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