1

I would like to check if an item exists in an array:

 protocol Item {
        var name: String! {get set}
        var value: Int! {get set}
    }

class UserList {
    var items: [Item]!

    func checkItem(item: Item) -> Bool{
        if items.contains(where: {$0 === item}) {  // Error
            return true
        }
        return false
    }
}

I get this error:

Binary operator '===' cannot be applied to two 'Item' operands

2 Answers 2

1

If you really want to use identity operator (===) for your checkItem, you can declare your Item as a class protocol:

protocol Item: class {
    var name: String! {get set}
    var value: Int! {get set}
}

class UserList {
    var items: [Item]!

    func checkItem(item: Item) -> Bool{
        return items.contains {$0 === item}
    }
}

(I do not understand why you need implicitly unwrapped Optionals, so I have kept them there. But I myself would never use so many IUOs.)


But I wonder if identity is what you want:

class ClassItem: Item {
    var name: String!
    var value: Int!

    init(_ name: String, _ value: Int) {
        self.name = name
        self.value = value
    }
}
let myList = UserList()
myList.items = [ClassItem("aaa", 1), ClassItem("bbb", 2)]
var result = myList.checkItem(item: ClassItem("aaa", 1))
print(result) //->false

If the result false is not what you expect, you need to define your own equality for the Item and define your checkItem(item:) with it.

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

Comments

0

I always use this simple solution, that comes from objecitve-c

let array = ["a,b"]
if let _ = array.index(of: "b")
{
    //if "b" is in array         
}
else
{
    //if "b" is not in aray
}

Comments

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.