Reputation:
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"...]
Upvotes: 1
Views: 1610
Reputation: 11243
You can use compactMap
to get all the valid names in the array.
print( driverArr.compactMap({$0.name}) )
Upvotes: 4