Learn Courses My Dashboard

SwiftUI Slots challenge matching problem

Hi! Help me please to understand what’s wrong with my IF ELSE statements, I’m stuck. I want to make it add 5 points in case of ANY 2 matches and add 10 if all three matchs but it keeps adding 5 when matching 3 slots.

struct ContentView: View {

@State var credit = 1000
@State var slot1 = 1
@State var slot2 = 2
@State var slot3 = 3

var body: some View {
    
    VStack(spacing: 20.0) {
    Spacer()
        
    Text("SwiftUI Slots!")
        .padding().font(.largeTitle)
        Spacer()
    
    Text("Credits: \(credit)")
        Spacer()
   
    HStack {
        Image("fruit\(slot1)").resizable().aspectRatio(contentMode: .fit)
        Image("fruit\(slot2)").resizable().aspectRatio(contentMode: .fit)
        Image("fruit\(slot3)").resizable().aspectRatio(contentMode: .fit)
    }
        Spacer()
       
    Button("Spin") {
            
        slot1 = Int.random(in: 1...3)
        slot2 = Int.random(in: 1...3)
        slot3 = Int.random(in: 1...3)

        
        if slot1 == slot2 || slot2 == slot3 || slot1 == slot3 {
            credit += 5
        } else if slot1 == slot2 && slot1 == slot3  {
            credit += 10
        } else {
            credit -= 20
        }
        
        }.padding().padding([.leading, .trailing], 40)
        .foregroundColor(.white)
        .background(Color(.systemPink))
        .cornerRadius(25)
        .font(.system(size: 18, weight: .bold, design: .default))
        Spacer()
    }
}

}

@Lady-Keti

Try rearranging your if statement to this:

                if slot1 == slot2 && slot1 == slot3 {
                    credit += 10
                } else  if slot1 == slot2 || slot2 == slot3 || slot1 == slot3 {
                    credit += 5
                } else {
                    credit -= 20
                }

This will trap the scenario where you have all three matching first. If that is not the case then it will look for any two that match and if that is not the case then none are matching.

1 Like

Thanks a lot!!! Now I got it ))