SwiftData Quakes Sample app decoding errors from null magnitudes

Hi! I believe there might be a small bug in the SwiftData Quakes Sample App.^1 The Quakes app requests a JSON feed from USGS.https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php What seems to be breaking is that apparently earthquake entities from USGS can return with null magnitudes. That is throwing errors from the decoder:

struct GeoFeatureCollection: Decodable {
    let features: [Feature]

    struct Feature: Decodable {
        let properties: Properties
        let geometry: Geometry
        
        struct Properties: Decodable {
            let mag: Double
            let place: String
            let time: Date
            let code: String
        }

        struct Geometry: Decodable {
            let coordinates: [Double]
        }
    }
}

which is expecting mag to not be nil.

Here is my workaround:

struct GeoFeatureCollection: Decodable {
    let features: [Feature]

    struct Feature: Decodable {
        let properties: Properties
        let geometry: Geometry
        
        struct Properties: Decodable {
            let mag: Double?
            let place: String
            let time: Date
            let code: String
        }

        struct Geometry: Decodable {
            let coordinates: [Double]
        }
    }
}

And then:

extension Quake {
    /// Creates a new quake instance from a decoded feature.
    convenience init(from feature: GeoFeatureCollection.Feature) {
        self.init(
            code: feature.properties.code,
            magnitude: feature.properties.mag ?? 0.0,
            time: feature.properties.time,
            name: feature.properties.place,
            longitude: feature.geometry.coordinates[0],
            latitude: feature.geometry.coordinates[1]
        )
    }
}

Thanks for reporting the issue. I've filed a bug report (r.141027601) to track the issue, and hopefully get it fixed in the near future.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

SwiftData Quakes Sample app decoding errors from null magnitudes
 
 
Q