Type '()' cannot conform to 'view'

Hello I am trying to connect a method from a class into a view but it is popping up with type '()' cannot conform to 'view'. The error is at the call to the showcard method in the scroll view. The second block of code is the class I am calling it from and the method I am using. Thank you


        VStack{

            headerView

            ScrollView(.horizontal, showsIndicators: false){

                HStack(spacing: 10){

                    viewModel.showCard()

                }

            }

            Spacer()

        }

    }

    @MainActor class ViewModel: ObservableObject{

        @EnvironmentObject var wallet: Wallet

        

        func showCard() {

            ForEach(wallet.cards.indices, id:\

                    .self) { index in

                        CardView(card:

                                    self.wallet.cards[index])

                        .onTapGesture {

                            self.wallet.cards.indices.forEach{ index in

                                self.wallet.cards[index].isSelected = false

                            }

                            self.wallet.cards[index].isSelected.toggle()

                        }

                    }

        }

    }

}

hi,

what you list inside an HStack must be Views. the function viewModel.showCard() does not return a View (its signature is () -> Void). and your viewModel should not be in the business of creating Views anyway

what you want is something like this for your higher-level View:

ScrollView(.horizontal, showsIndicators: false){
    ForEach(wallet.cards, id:\ .self) { card in
        CardView(card: card)
            .onTapGesture { viewModel.selectCard(card) }
    }
}

then add the function viewModel.selectCard to update the isSelected property of the cards it maintains in its wallet.cards array.

hope that helps,

DMG

I don't know why you need a ViewModel (where else do you use) ?

If you don't need, you could try this:

struct ContentView: View {
    @EnvironmentObject var wallet: Wallet
    
    var body: some View  {
        
        ScrollView(.horizontal, showsIndicators: false) {
            
            HStack(spacing: 10) {
                
                ForEach(wallet.cards.indices, id:\.self) { index in
                    CardView(card: self.wallet.cards[index])
                        .onTapGesture {
                            self.wallet.cards.indices.forEach { index in
                                self.wallet.cards[index].isSelected = false
                            }
                            self.wallet.cards[index].isSelected.toggle()
                        }
                }
                
            }
            
        }
    }
}
Type '()' cannot conform to 'view'
 
 
Q