gpt4 book ai didi

json - 解码JSON数据时Type不符合Identifiable

转载 作者:行者123 更新时间:2023-12-04 15:07:43 26 4
gpt4 key购买 nike

我正在尝试为我的应用程序使用不同的 json 文件。原始 json 文件中有 "id",但新的 json 文件中有 "nr"。所以我将代码更改为:

import Foundation

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

早期的代码使用 let id: Int 而不是 let nr: Int。更改此代码后,出现错误:

Type pokemon does not conform to protocol identifiable

这是旧的 json 文件:

{
"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
},

鉴于新文件有 "nr" 而不是 "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"
],

我搜索后发现我需要使用 id 因为它用作标识符。如何使用那个“nr”而不是 id?或任何其他方式在新的 json 文件中使用 id?

最佳答案

你可以使用可计算的属性,比如

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

关于json - 解码JSON数据时Type不符合Identifiable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65762382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com