0

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'
1

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

This will compare pointers, not object equality iirc (I didn't downvote).
Added an alternate solution, hopefully the downvoter might like it :)
In my scenario, pointer comparison was fine. I appreciate both answers. Thanks!
1

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.

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.