I'm using the library CodableFirebase to decode and encode data when working with Google's Firestore. It works great, except if a value is not defined in the database but is a property of the class. I am wondering how do you define the class so that when the snapshot comes back from Firebase it doesn't puke on the nil value.
Here's a simple example of what is happening.. This would be my class definition.
class TimeThing: Codable {
var requestedTime: Double?
var createdTime: Double?
init(
requestedTime: Double? = 0,
createdTime: Double? = 0
) {
self.requestedTime = requestedTime
self.createdTime = createdTime
}}
And this would be the error that's getting thrown. createdTime, in this case, has a value in Firestore where 'requestedTime' doesn't.
Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "requestedTime", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))
I realize I'm missing something fundamental, but unfortunately I'm just not sure what that is. What do I need to do to my class to set defaults that will not blow up my try block when experiencing a nil value from Firestore?
Thanks!!
Turns out the core of the issue was that the defaults in the class were incorrectly defined.
class TimeThing: Codable {
var requestedTime: Double?
var createdTime: Double?
init(
requestedTime: Double? = 0,
createdTime: Double? = 0
) {
self.requestedTime = requestedTime
self.createdTime = createdTime
}}
should have been
class TimeThing: Codable {
var requestedTime: Double? = 0
var createdTime: Double? = 0
init(
requestedTime: Double,
createdTime: Double
) {
self.requestedTime = requestedTime
self.createdTime = createdTime
}}
Once I fixed that, the defaults were there for CodableFirebase to decode.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.