M2L2 foundation 2021 - error using contain with object

Hi there !!
I am trying to use contains : deck.contains(card), but the error message is

“Cannot convert value of type ‘ContentView.PlayingCard’ to expected argument type ‘(ContentView.PlayingCard) throws → Bool’”

Logically if I can search string in a array of string, I can search a object in array of Object isn’ it?

Please your help.

//
//  ContentView.swift
//  Lesson12-Excercise
//
//  Created by Orlando J on 22-07-23.
//

import SwiftUI

struct ContentView: View {

    @State var mensaje:String = ""
    @State var deck: [PlayingCard] = [PlayingCard]()
    
    var body: some View {

        VStack {
            Text(mensaje)
                .font(.largeTitle)
            HStack {
                Button {
                    // Action
                    var card = PlayingCard(num: Int.random(in: 0...13), palo: "a")
                    deck.append(card)
                    if deck.contains(card) {
                        mensaje = "Generated duplicat card"
                    }

                    //var palo = deck.palo.randomElement()

                } label: {
                    Text("Button1")
                }
                .padding()
                .background(.blue)
                .cornerRadius(12)

                
                Button {
                    // Action2
                } label: {
                    Text("Button2")
                }
                .padding()
                .background(.blue)
                .cornerRadius(12)

            }
            .padding()
            .background(Color.yellow)
            .cornerRadius(12)
            .foregroundColor(.white)
        }
        
    }
    
    struct PlayingCard {
        var num:Int //= [1,2,3,4,5,6,7,8,9,10,11,12]
        var palo:String //= ["Spades","Clubs","Hearts","Diamonds"]
    }
}

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

The error message you are getting is unfortunately not very helpful. In some cases the compiler does not accurately identify what is wrong.

Although by no means obvious, the answer is to make the PlayingCard conform to the protocol Equatable which means to do this:

    struct PlayingCard: Equatable {
        var num:Int //= [1,2,3,4,5,6,7,8,9,10,11,12]
        var palo:String //= ["Spades","Clubs","Hearts","Diamonds"]
    }

which will allow you to use the syntax

if deck.contains(card) { 
    etc
    etc

The other error that you will notice is that your .background() modifier where you are specifying a color for the Buttons background should be .background(Color.blue)

Hope that helps

1 Like

Thanks very much. It’s works!