Hackmodford
Hackmodford

Reputation: 3970

How to find if array contains object

I have created a custom class called MenuItem:

import Foundation

class MenuItem {

    var title: String
    var tag: Int
    var image: UIImage

    init (title: String, tag: Int, image: UIImage) {
        self.title = title
        self.tag = tag
        self.image = image
    }

}

I am adding these objects to an array.

How can I check if an array contains a specific menu item?

This is a simplified version of what I have tried.

let menuOptionInventory = MenuItem(title: "Inventory", tag: 100, image: UIImage(imageLiteral: "871-handtruck"))
var menuOptions = [MenuItem]()
menuOptions.append(menuOptionInventory)

if (menuOptions.contains(menuOptionInventory)) {
    //does contain object
}

When I do this I get this error message:

Cannot convert value of type 'MenuItem' to expected argument type '@noescape (MenuItem) throws -> Bool'

Upvotes: 0

Views: 2137

Answers (2)

Matt Le Fleur
Matt Le Fleur

Reputation: 2856

Try this out:

if menuOptions.contains( { $0 === menuOptionInventory } ) {
    //does contain object
}

Edit: As JAL pointed out this does compare pointers.

So instead you could override the == operator specifically for a comparison between two MenuItem objects like this:

func == (lhs: MenuItem, rhs: MenuItem) -> Bool {
    return lhs.title == rhs.title && lhs.tag == rhs.tag && lhs.image == rhs.image
}

And then you could use the contain method closure to perform a comparison between the objects.

if menuOptions.contains( { $0 == menuOptionInventory } ) {
    //does contain object
}

Upvotes: 2

JAL
JAL

Reputation: 42449

A few issues:

contains takes in a closure. You would need to do your comparison like this:

if menuOptions.contains( { $0 == menuOptionInventory } ) {
    // do stuff
}

But now you'll get the issue that == cannot be applied to two MenuItem objects. Conform your object to Hashable and Equatable and define how two MenuItem objects are equal, or use a base class that conforms to Hashable and Equatable for you, such as NSObject.

Upvotes: 1

Related Questions