1

I'm trying to create a simple app that keeps count of how buttons in a list of clothing items have received more than 5 taps.

I've tried using the code below, but keep getting the error "Cannot convert value of type 'ContentView.clothing' to expected argument type 'Int'" in the line if clothes[i].taps >= 5.

I feel like somehow this might be related to the fact that I've tried to pass a whole struct as a parameter of the func. Perhaps I'm not meant to do this?

Any guidance much appreciated!

import SwiftUI



struct ContentView: View {
    
    struct clothing {
        var type: String
        var taps: Int
    }

    @State var currentClothes = [
        clothing(type: "tshirt", taps: 0),
        clothing(type: "dress", taps: 0)
    ]

    
    var body: some View {
        NavigationView{

            List{
            
            ForEach(0..<currentClothes.count) { i in
                Button("\(currentClothes[i].type)") {
                    self.currentClothes[i].taps += 1
                    print(currentClothes)
                }
                    
                }
            }
            Text("\(tapCount(clothes: currentClothes))")
        }
    }
    
    func tapCount(clothes: [clothing]) -> Int {

        var total = 0
        for i in clothes {
            if clothes[i].taps >= 5
            {total += 1}
         }
        
         return total
        

    }
}

1 Answer 1

4

It should be

for i in clothes {
    if i.taps >= 5
    {total += 1}
}

not

for i in clothes {
    if clothes[i].taps >= 5
    {total += 1}
}

because you are looping over clothes, not clothes.count or something. i is a clothing, not an Int.

As a side note, try to keep your classes and structs Uppercased. clothing would be better off as Clothing.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I was close it seems!
@FPL you were! I added a note on naming conventions btw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.