Home > Net >  Type 'PlayerData' does not conform to protocol 'Decodable' and 'Encodable&#
Type 'PlayerData' does not conform to protocol 'Decodable' and 'Encodable&#

Time:12-29

The class PlayerData includes an array of the class Player and to save an object of PlayerData to UserDefaults I confirmed it to Codable Protocol. But I have these errors.

"Type 'PlayerData' does not conform to protocol 'Decodable'"

import Foundation
import SwiftUI

class Player {
    var name: String
    var id: Int
    init(name: String, id: Int){
        self.name = name
        self.id = id
    }
}


class PlayerData: Codable {   // <- error here
    var latestId: Int
    var player: [Player] = []
    init(){
        latestId = 0
        player = []
    }
}


func savePlayers(data: PlayerData) {
    let encoder = JSONEncoder()
    if let encoded = try? encoder.encode(data) {
        UserDefaults.standard.set(encoded, forKey: "saved_data")
    }
}

func pullPlayers() -> PlayerData {
    if let data = UserDefaults.standard.object(forKey: "saved_data") as? Data {
        let decoder = JSONDecoder()
        if let savedData = try? decoder.decode(PlayerData.self, from: data) {
            return savedData
        }
    }
}

Thank you for your help :)

CodePudding user response:

Player should conform also

class Player : Codable {
  • Related