有没有办法修复这个错误:
Immutable property will not be decoded because it is declared with an initial value which cannot be overwritten这个错误显示在let id = UUID()旁边,我知道它为什么在那里,但是将id设置为var不起作用,因为JSONDecoder不能解码该结构。程序运行良好,但错误非常恼人,因为有15个错误。我对swift有些陌生,所以如果这段代码中有任何错误,请随时批评它们。
import Foundation
struct Ability: Codable, Identifiable{
let id = UUID()
let name: String
let url: String
}
struct Abilities: Codable, Identifiable {
let id = UUID()
let ability: Ability
let is_hidden: Bool
let slot: Int
}
struct Forms: Codable, Identifiable {
let id = UUID()
let name: String
let url: String
}
struct Species: Codable, Identifiable {
let id = UUID()
let name: String
let url: String
}
struct OfficialArtwork: Codable, Identifiable {
let id = UUID()
let front_default: String?
}
struct Other: Codable {
//let dream_world: DreamWorld
let art: OfficialArtwork
enum CodingKeys: String, CodingKey {
case art = "official-artwork"
}
}
struct Sprites: Codable, Identifiable {
let id = UUID()
let other: Other
}
struct Type: Codable, Identifiable {
let id = UUID()
let name: String
let url: String
}
struct Types: Codable, Identifiable {
let id = UUID()
let type: Type
}
struct Stat: Codable, Identifiable {
let id = UUID()
let name: String
let url: String
}
struct Stats: Codable, Identifiable {
let id = UUID()
let base_stat: Int
let stat: Stat
}
struct Move: Codable, Identifiable {
let id = UUID()
let name: String
let url: String
}
struct Moves: Codable, Identifiable {
let id = UUID()
var move: Move
}
struct APIInfo: Codable, Identifiable {
let id = UUID()
let abilities: [Abilities]
let base_experience: Int
let forms: [Forms]
let height: Int
//let held_items:
let location_area_encounters: String
let moves: [Moves]
let name: String
//let past_types:
let species: Species
let sprites: Sprites
let stats: [Stats]
let types: [Types]
let weight: Int
}
struct Results: Codable, Identifiable {
let id = UUID()
let name: String
let url: String
}
struct Link: Codable, Identifiable {
let id = UUID()
let results: [Results]
}
class Data {
func fetchName(completion: @escaping ([Results]) -> () ){
guard let url = URL(string: "https://pokeapi.co/api/v2/pokemon/?limit=1118") else {return}
URLSession.shared.dataTask(with: url) { data, response, error in
let jsonResult = try! JSONDecoder().decode(Link.self, from: data!)
DispatchQueue.main.async {
completion(jsonResult.results)
}
}.resume()
}
func fetchInfo(link: String, completion: @escaping (APIInfo) -> () ){
guard let url = URL(string: link) else {
print("error")
return
}
URLSession.shared.dataTask(with: url) {data, response, error in
let jsonResult = try! JSONDecoder().decode(APIInfo.self, from: data!)
DispatchQueue.main.async {
completion(jsonResult)
}
}.resume()
}
}发布于 2021-09-17 18:16:09
例如,添加CodingKeys并省略id
struct Ability: Codable, Identifiable{
let id = UUID()
let name: String
let url: String
private enum CodingKeys: String, CodingKey { case name, url }
}https://stackoverflow.com/questions/69227848
复制相似问题