Type does not conform to Identifiable when decoding JSON data

Viewed 398

Im trying to use a different json file for my app. The original json file has "id" in it but the new json file has "nr". So I changed my code to this:

import Foundation

struct Pokemon: Decodable, Identifiable {
    let nr: Int
    let name: String
    let imageUrl: String
    let type: String
} 

Earlier code had let id: Int instead of let nr: Int. After changing this code, I get the error:

Type pokemon does not conform to protocol identifiable

This was the old json file:

{
    "attack": 49,
    "defense": 49,
    "description": "Bulbasaur can be seen napping in bright sunlight.\nThere is a seed on its back. By soaking up the sun’s rays,\nthe seed grows progressively larger.",
    "evolutionChain": [
      {
        "id": "2",
        "name": "ivysaur"
      },
      {
        "id": "3",
        "name": "venusaur"
      }
    ],
    "height": 7,
    "id": 1,
    "imageUrl": "https://firebasestorage.googleapis.com/v0/b/pokedex-bb36f.appspot.com/o/pokemon_images%2F2CF15848-AAF9-49C0-90E4-28DC78F60A78?alt=media&token=15ecd49b-89ff-46d6-be0f-1812c948e334",
    "name": "bulbasaur",
    "type": "poison",
    "weight": 69
  },

Whereas new file has "nr" instead of "id":

{
    "nr": 1,
    "nrp": "001",
    "name": "Bulbasaur",
    "class": "Seed Pok\u00e9mon",
    "icon": "https:\/\/s6.postimg.org\/z17mvgtgx\/001.png",
    "art": "https:\/\/s6.postimg.org\/bu799hi5t\/001.png",
    "types": [
      "Grass",
      "Poison"
    ],

I found after searching that I need to use id as it is used as identifier. How to use that "nr" instead of id? Or any other way to use id in new json file?

1 Answers

You can use computable property, like

struct Pokemon: Decodable, Identifiable {
    var id: Int { nr }                       // << here !!
    let nr: Int
    let name: String
    let imageUrl: String
    let type: String
} 
Related