Stuck using variable in the tex statement

I have two simple tests initially triggered by a title of a game setting: "Highest score Wins" or rule.hasSuffix("wins."). The code in both cases looks for the highest score and in the latter case checks to see if a target score has been achieved. This work fine. But when I display the final results, the first works fine and the latter fails to display the name; defaulting to the No One Wins - which is incorrect. The relevant pieces of the code are:

   case rule == "Highest score Wins":
        // Find the highest score
        let maxScore = scores.max(by: { $0.1 < $1.1 })?.1 ?? 0
        let topScorers = scores.filter { $0.1 == maxScore }
        gameIsDraw = topScorers.count > 1
        winner = topScorers.count == 1 ? topScorers.first?.0 : nil

// This work and will display the winner name correctly - see below

    case rule.hasSuffix("wins."):
        // "Player to reach X wins."
        let topScorers = scores.filter { $0.1 >= target }
        if !topScorers.isEmpty {
            let maxScore = scores.max(by: { $0.1 < $1.1 })?.1 ?? 0
            let topScorers = scores.filter { $0.1 == maxScore }
            gameIsDraw = topScorers.count > 1
            winner = topScorers.count == 1 ? topScorers.first?.0 : nil

// This works but does not display the name

//This is the section that displays the names (winner)

                if gameIsDraw {
                    Text("The Game is a Draw")
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(.orange)
                } else {
                    Text("Game Over!")
                        .font(.largeTitle)
                        .bold()

                    Text("\(winner?.playername ?? "No One") Wins!")
                        .font(.title)
                        .foregroundColor(.green)
                }

I have tried everything, but am losing the will to live

So that means winner is nil.

There is likely an error here:

        gameIsDraw = topScorers.count > 1
        winner = topScorers.count == 1 ? topScorers.first?.0 : nil

gameIsDraw is true if count > 1

But winner is defined when count == 1

It should probably be

        winner = topScorers.count >= 1 ? topScorers.first?.0 : nil

Wow, that was incredibly quick response. Thank you. I am sorry to say that that has not fixed it. The crazy thing is that only real difference between the working section and this one is that it is testing for the target being met. Now meeting the target and setting isGameOver to true works, but the getting the name of the player into winner fails. but this is roughly the same code as the working section and the replacement of the == with >= wasn't needed in the "Highest score Wins" code, as it works. Do you have any further ideas I could try?

I do think winner is nil.

Where do you call the case rule… are called. Are you sure they are ever called ?

Please show complete code to allow for testing.

There are a number of views to create game types and players. Also a .xcddatamodeld with the Attributes of the PlayerDataItems. then the code for Scoring is:

Could you test:

    case rule.hasSuffix("wins."):
        // "Player to reach X wins."
        let topScorers = scores.filter { $0.1 >= target }
        if !topScorers.isEmpty {
            print("topScorers not Empty")  // <<-- ADD THIS
            let maxScore = scores.max(by: { $0.1 < $1.1 })?.1 ?? 0
            let topScorers2 = scores.filter { $0.1 == maxScore } // <<-- CHANGE to topScorers2
            gameIsDraw = topScorers2.count > 1
            winner = topScorers2.count == 1 ? topScorers2.first?.0 : nil

And tell what you get.

A comment. Even if the syntax is correct,

     let maxScore = scores.max(by: { $0.1 < $1.1 })?.1 ?? 0

is hard to read.

.1 is a property, it would be so easier to read by using the property name

<0x105e17860> Gesture: System gesture gate timed out. -[RTIInputSystemClient remoteTextInputSessionWithID:performInputOperation:] perform input operation requires a valid sessionID. inputModality = Keyboard, inputOperation = <null selector>, customInfoType = UIEmojiSearchOperations topScorers not Empty -[RTIInputSystemClient remoteTextInputSessionWithID:performInputOperation:] perform input operation requires a valid sessionID. inputModality = Keyboard, inputOperation = <null selector>, customInfoType = UIEmojiSearchOperations

the score array holds the player name and their score. This is in this function: private func addRoundScores() { // Update total scores

    for player in players {
        if let scoreString = currentScores[player.playerid ?? ""],
           let score = Int(scoreString) {
            let currentTotalScore = playerScores[player.playerid ?? ""] ?? 0
            playerScores[player.playerid ?? ""] = currentTotalScore + score
        }//End of let score = Int(scoreString)
    }// End of for player in players
    
    // Store the current round scores
    rounds.append(currentScores.compactMapValues { Int($0) })
    
    // Clear input fields for the next round
    currentScores = [:]
    // Mark that scores have been added
    hasScoresBeenAdded = true

    dismissKeyboard() // Hide the keyboard after adding scores

There is a n entity called:PlayerDataItem with two Attributes:PlayerID and PlayerName

and a declaration: @State private var playerScores: [String: Int] = [:] // Store total scores by playerid (String)

MaxScore is not declared anywhere other then in this function so my guess is that is simply replicating the Player Name and Score. If I am honest this bit of code was generated, after a lot of trial and error by ChatBT.

If I am honest this bit of code was generated, after a lot of trial and error by ChatBT.

That's a problem when you don't understand the code you use.

Did you ask CGT to solve the issue, as they proposed the code ? 😉

Returning to human answer, you didn't answer my question. Did you test the code I sent you? What is the result ?

You are right of course and yes I did ask ChatBT to solve it, but it was always incorrect; so yes many times. I did test it as you asked and I posted above the print out of the code you gave me. I also tried to removed the comments in the line //isGameOver = true to force the case: rule == "Highest score Wins" section to fire off the display with the results and you have guessed it; that then failed and gave me a No One Wins. So I started seeing if I could stop using this isGameOver bool until I absolutely had by using an intermediate variable. let peter = true, then later in the sequence and away from the funtion a test that said: if peter = true { isGameOver = true}. it didn't like that one bit so I removed it. Still looking to try and understand what is happening and I fully accept that I am very new to Swift and xCode so have probably created the problem unnecessarily. Any help would be much appreciated.

So yesterday I had another session with ChatBT and this time it recommended that I use a Class too resolve the issue. This was:class GameState: ObservableObject { and following that all my variables were marked as @published and many of my lines were change to include the gamestate. i.e: gameState.currentScores[player.playerid ?? ""] = "-0" Now I am afraid, I have no idea what this is all about but it now all works. I will dig deeper into understanding this but I would like to thank Claude31 for his interest and help. Thank you

Stuck using variable in the tex statement
 
 
Q