Search code examples
swiftuikitmkannotation

Type 'Location' does not conform to protocol 'Decodable' -- MKAnnotation UIKit


I'm a French newbie in Swift programmation and I want to show annotations from a JSON file with UIKit (not swiftUI because I want to cluster my annotations). I create a class who are decodable and a MKAnnotation and I have an issue : "Type 'Location' does not conform to protocol 'Decodable'"

Thanks you very much for yours answers !

Here my Location class


class Location: NSObject, Decodable, Identifiable, MKAnnotation {
    
    var id: Int
    var name: String
    var latitude: Double
    var longitude : Double
    var coordinate:  CLLocationCoordinate2D
    
    
    init(id : Int, name : String, latitude : Double, longitude : Double){
        
        self.id = id
        self.name = name
        self.longitude = longitude
        self.latitude = latitude
    }
    
}

And my JsonFile

{
  "locations": [
    {
      "id": 0,
      "name": "New York City",
      "latitude": 40.71,
      "longitude": -74
    },
    {
      "id": 1,
      "name": "Barcelona",
      "latitude": 41.38,
      "longitude": 2.17
    }

Solution

  • Make coordinate a computed property

    var coordinate:  CLLocationCoordinate2D{
        CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
    

    or

    var coordinate:  CLLocationCoordinate2D{
        get{
            CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        }
        set{
            latitude = newValue.latitude
            longitude = newValue.longitude
        }
    }