Learn Courses My Dashboard

Lesson 12 Challenge (14 day challenge)

I just started on challenge 12 but I can’t remember how to create functions or how to set up a random number generator in Swift.
The code I have so far is below.

//
//  ContentView.swift
//  Shared
//
//  Created by Eric Beecroft on 9/7/21.
//

import SwiftUI

struct ContentView: View {
    @State private var score = 0;
    var body: some View {
        VStack{
            Text(String(score))
            HStack{
                Button(action: {
                    score += 1
                }, label: {
                    Text("Increase")
                })
                
                Button(action: {
                    score -= 1
                }, label: {
                    Text("Decrease")
                })
            }
        }
        Text("Hello, world!")
            .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Lesson 7 covered creating funcs in your ContentView
Lesson 11 covered how to get and use a random Int.

Generally, a func is within the ContentView, after the body.
The random Int comes from this type of form
Int.random(in: 1...10)

I changed up the code a bit. Is this way to do it or am I missing something?

//
//  ContentView.swift
//  Shared
//
//  Created by Eric Beecroft on 9/7/21.
//

import SwiftUI

struct ContentView: View {
    @State private var score = 0;
    func Increment()
    {
        if(score > 50) {score -= Int.random(in: 1...10);}
        else {score += Int.random(in: 1...10);}
    }
    
    func Decrement()
    {
        if(score < 0) {score += Int.random(in: 1...10);}
        else {score -= Int.random(in: 1...10);}
    }
    
    var body: some View {
        VStack{
            Text(String(score))
            HStack{
                Button(action: {
                    Increment()
                }, label: {
                    Text("Increase")
                })
                
                Button(action: {
                    Decrement()
                }, label: {
                    Text("Decrease")
                })
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

You can check the solution from Chris in the resource section at the beginning

If it works great! With coding there’s ALWAYS multiple ways to do something