Learn Courses My Dashboard

Module 1 Lesson 12:

it was a brilliant question, here is how to solve it in a simple format:

import SwiftUI

struct ContentView: View {
    @State var a = 0
    // setting a general case
    @State var increaseby = true
    var body: some View {
        VStack
        {
            Text("Score: "+String(a))
            Button("Click me") {
                func increase(){
                    a += Int.random(in: 1...10)
                }
                func decrease(){
                    a -= Int.random(in: 1...10)
                }
                if increaseby {
                    if a<50
                    {
                        increase()
                    }else{
                        increaseby = false
                    }
                }else{
                    if(a>0){
                        decrease()
                    }else{
                        increaseby = true
                    }
                }
                
            }
        
    }
}

@Sam_Grover

Whilst that works you should never have functions defined inside a Button in the way you have coded it.

Functions should be defined at the same level as var body some View.

The objective of all SwiftUI projects is also to have as little logic inside the View as possible.

Consider this alternative solution of your code:

struct ContentView: View {
    @State var a = 0
    // setting a general case
    @State var increaseby = true
    
    var body: some View {
        VStack {
            Text("Score: " + String(a))
            Button("Click me") {
                if increaseby {
                    increase()
                } else {
                    decrease()
                }
            }
        }
    }

    func increase() {
        a += Int.random(in: 1...10)
        if a >= 50 {
            increaseby = false
        }
    }
    func decrease() {
        a -= Int.random(in: 1...10)
        if a <= 0 {
            increaseby = true
        }
    }
}
2 Likes