user6384363
user6384363

Reputation:

How do I initialize an alert within a function using SwiftUI?

I'm trying to add an alert when gameOver() is called. "Result of 'Alert' initializer is unused". How do I initialize the alert I created?

func gameOver() {
    round = 0
    score = 0
    self.changeTarget()
}

Solution Attempt:

func gameOver() {
    round = 0
    score = 0
    self.changeTarget()
    Alert(title: Text("Game Over"),
    message: Text("Thanks for playing"),
    dismissButton: Alert.Button.default( Text("Play Again")))
}

Upvotes: 1

Views: 1747

Answers (2)

user6384363
user6384363

Reputation:

This ended up working to display a game over alert.

.alert(isPresented: $alertIsVisible) { () -> Alert in
    let roundedValue = sliderValueRounded()
    if self.round == 5 {
        return Alert(title: Text("Game Over"), message: Text("Your score was \(score)."), dismissButton: .default(Text("Play Again")) {
        self.startOver()
        })
    } else {
    return Alert(title: Text(alertTitle()), message: Text("The slider's value is \(roundedValue). \n" + "You scored \(pointsForCurrentRound()) points!"), dismissButton: .default(Text("Play Again")){
        self.changeTarget()
        self.round += 1
        })}
}

Upvotes: 0

Hrabovskyi Oleksandr
Hrabovskyi Oleksandr

Reputation: 3275

In SwiftUI framework you have several options for implementing Alert, for example:

func alert<Item>(item: Binding<Item?>, content: (Item) -> Alert) -> some View where Item : Identifiable

func alert<Item>(item: Binding<Item?>, content: (Item) -> Alert) -> some View where Item : Identifiable

Here is a simple example of using the first option:

struct GameOverAlert: View {

    @State private var round = 0
    @State private var score = 0
    @State private var restartGame = false // variable for showing alert

    var body: some View {

        VStack {

            Text("round: \(round)")
            Text("score: \(score)")

            HStack { // used this style just for brevity
                Button(action: { self.score += 1 }) { Text("add score") }
                Button(action: { self.gameOver() }) { Text("over game") }
            }
            Spacer() // only for presenting result

        }
        .alert(isPresented: $restartGame) {
            Alert(title: Text("Your score is \(score)"), dismissButton: .default(Text("Play again")) {
                self.playAgain()
            })
        }


    }

    // described logic here, but it should be in some ViewModel, etc
    private func gameOver() {
        restartGame = true
    }

    private func playAgain() {
        score = 0
        round = 0
    }

}

with code above you'll achieve this:

enter image description here

Upvotes: 1

Related Questions