4

I'm relatively new with Firebase's new Cloud Firestore and I'm having difficulty trying to map data to/from. I've tried following documentation via Google online, but it has some issues I cannot figure out the origin of.

  1. When I try to cast from [String : Any] to my custom struct, the documentation suggested I try the following:
docRef.getDocument { (document, error) in
            let result = Result {
                try document.flatMap {
                    try $0.data(as: City.self)
                }
            }
            switch result {
            case .success(let city):
                if let city = city {
                    print("City: \(city)")
                } else {
                    print("Document does not exist")
                }
            case .failure(let error):
                print("Error decoding city: \(error)")
            }
        }

However, this produced an error on the line $0.data(as: City.self) with Value of type 'NSObject' has no member 'data'.

  1. When I try to write data as a Document to a new collection, the documentation suggests I try the following:
do {
    try db.collection("cities").document("LA").setData(from: city)
} catch let error {
    print("Error writing city to Firestore: \(error)")
}

But this also produces an error on the .setData(from: city) with Argument labels '(from:)' do not match any available overloads.

Does anyone have any familiarity with this to try to provide additional clarity for casting Firestore data to custom structs? I understand my structs are intended to be codable.

Kyle Beard
  • 604
  • 5
  • 18

2 Answers2

8

If I understand correctly, you are having the same issue I had a few days ago: Firebase (Cloud Firestore) - How to convert document to a custom object in Swift 5?

The key here is to do import FirebaseFirestoreSwift explicitly instead of just doing import Firestore.

  • 1
    Why didn't I think of that! Thank you! I wish the documentation mentioned this more specifically as it says it's optional in the podfile example. – Kyle Beard Jan 08 '20 at 01:02
  • You are welcome:D I was also puzzled by this until I got the reply from the Firebase team. I've already suggested that they add this explicitly:) – Tianyao 'Till' Chen Jan 08 '20 at 12:41
  • My dude, thank you! This is the solution. Top man. Anyone looking at this, make sure to add pod 'FirebaseFirestoreSwift' to your podfile as well. – テッド Mar 14 '20 at 14:58
  • Haha. No problem. I was actually really struggling a lot. And I'm glad this helped:D – Tianyao 'Till' Chen Mar 15 '20 at 15:02
0

Never found reasoning for the errors but...

  1. I ended up converting $0.data to a JSON Data object and then decoded as such appropriately in order to map the dictionary to the struct.
  2. How can I use Swift’s Codable to encode into a dictionary?
Kyle Beard
  • 604
  • 5
  • 18