Search code examples
swiftswiftuiencodeappstorage

Encode a struct to be saved in AppStorage


Currently trying to build my first app in swiftUI. The part I thought would be the easiest as become a nightmare... save a struct in AppStorage to be available upon restart of the app

I got two struct to save. The first is for player and I have implemented the RawRepresentable

struct Player: Codable, Identifiable {
    let id: Int
    let name: String
    let gamePlayed: Int
    let bestScore: Int
    let nbrGameWon: Int
    let nbrGameLost: Int
    let totalScore: Int?

}

typealias PlayerList = [Player]
extension PlayerList: RawRepresentable {
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),
            let result = try? JSONDecoder().decode(PlayerList.self, from: data)
        else {
            return nil
        }
        self = result
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),
            let result = String(data: data, encoding: .utf8)
        else {
            return "[]"
        }
        return result
    }
}

Calling in my view this way:

struct AddPlayerView: View {
    @State var name: String = ""
    @State var isDisabled: Bool = false
    @State var modified: Bool = false
    @AppStorage("players") var players: PlayerList = PlayerList()
    ...
}

The above works, now I also want to save the current game data, I have the following struct:

struct Game: Codable, Identifiable {
    var id: Int
    var currentPlayerIndexes: Int
    var currentRoundIndex: Int?
    var dealerIndex: Int?
    var maxRounds: Int?
    var dealResults: [Int: Array<PlayerRoundSelection>]?
    var currentLeaderIds: Array<Int>?
    var isGameInProgress: Bool?
}

extension Game: RawRepresentable {
    public init?(rawValue: String) {
        if rawValue == "" {
            // did to fix issue when calling AppStorage, but it is probably a bad idea
            self = Game(id:1, currentPlayerIndexes:1)
        }
        else {
            guard let data = rawValue.data(using: .utf8),
                let result = try? JSONDecoder().decode(Game.self, from: data)
            else {
                return nil
            }
            self = result
        }
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),
            let result = String(data: data, encoding: .utf8)
        else {
            return ""
        }
        return result
    }
}

As soon as I try to modify the struct, it calls rawValue and the encoding fails with the following:

error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated

error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0x7ffee49bbff8).

Here part of the code that access the struct:

struct SelectPlayersView: View {
    @AppStorage("currentGame") var currentGame: Game = Game(rawValue: "")!
    ....
NavigationLink(
                    destination: SelectModeTypeView(), tag: 2, selection: self.$selection) {
                    ActionButtonView(text:"Next", disabled: self.$isDisabled, buttonAction: {
                        var currentPlayers = Array<Int>()
                        self.players.forEach({ player in
                            if selectedPlayers.contains(player.id) {
                                currentPlayers.insert(player.id, at: currentPlayers.count)
                            }
                        })
    // This used to be a list of indexes, but for testing only using a single index
    self.currentGame.currentPlayerIndexes = 6
                        self.selection = 2
                    })
...

I found the code to encode here: https://lostmoa.com/blog/SaveCustomCodableTypesInAppStorageOrSceneStorage/

My understanding is that with the self in the encode, it generate an infinite loop hence the bad access.

I have really no knowledge how to properly encode this, any help, links would be appreciated


Solution

  • I had the same problem and I wanted to share my experience here.

    I eventually found that apparently you cannot rely on the default Codable protocol implementation when used in combination with RawRepresentable. So when I did my own Codable implementation, with CodingKeys and all, it worked!

    I think your Codable implementation for Game would be something like:

    enum CodingKeys: CodingKey {
        case currentPlayerIndexes
        case currentRoundIndex
        // <all the other elements too>
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.currentPlayerIndexes = try container.decode(Int.self, forKey: .currentPlayerIndexes)
        self.currentRoundIndex = try container.decode(Int.self, forKey: .currentRoundIndex)
        // <and so on>
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(currentPlayerIndexes, forKey: .currentPlayerIndexes)
        try container.encode(currentRoundIndex, forKey: .currentRoundIndex)
        // <and so on>
    }
    

    I then wondered why your Player coding/decoding did work and found that the default coding and decoding of an Array (i.e. the PlayerList, which is [Player]), works fine.