Abdou023
Abdou023

Reputation: 1664

Swift 3: Check for item in an array

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

Upvotes: 1

Views: 1169

Answers (2)

Bws Sluk
Bws Sluk

Reputation: 518

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
}

Upvotes: 0

OOPer
OOPer

Reputation: 47886

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.

Upvotes: 1

Related Questions