问题
jumping into FireStore following the official documentation, trying to connect a Struct to Firestore/setdata functions, according to the documentation, Cloud Firestore converts the objects to supported data types and can handle custom classes
so the struct goes as follow :
public struct City: Codable {
let name: String
let state: String?
let country: String?
let isCapital: Bool?
let population: Int64?
enum CodingKeys: String, CodingKey {
case name
case state
case country
case isCapital = "capital"
case population
}
}
and uploading data as follow. Firestore wants a [String: Any] type of data :
let city = City(name: "Los Angeles",
state: "CA",
country: "USA",
isCapital: false,
population: 5000000)
do {
try db.collection("cities").document("LA").setData(city) // <--- Cannot convert value of type 'postData' to expected argument type '[String : Any]'
} catch let error {
print("Error writing city to Firestore: \(error)")
}
any idea how to solve this ?
回答1:
I think setting the data should look more like this:
db.collection("cities").document("LA").setData([
cityName: city.name,
cityState: city.state,
// And so on...
])
Those are Key:Value-Pairs. On the left side is the field name in FireStore and the right side the value that should be written in it.
回答2:
so the only way I found to connect custom Structs (or classes) is a bit ugly, but it works but defining the struct as follow
public struct City: Codable {
let name: String
let state: String
var DataToPass : [String:Any] {
return [
"name" : self.name,
"state" : self.state
]
}
and then simply pass it to FStore using datapass :
let city = City(name: "Los Angeles",
state: "CA")
db.collection("cities").document("LA").setData(city.dataToPass)
来源:https://stackoverflow.com/questions/61955190/firestore-type-does-not-match-stringany