3

I have a custom array like this

let moreMenuItem = [MoreMenuItem(title: "number1", imageName: "rate"),
                    MoreMenuItem(title: "number2", imageName: "followFacebook"),
                    MoreMenuItem(title: "number3", imageName: "email")]

and this is my model class

class MoreMenuItem {

    var title: String?
    var imageName: String?

    init(title: String, imageName: String) {
        self.title = title
        self.imageName = imageName }
    }
}

now let say I have a string "number3" and I would like to check if my array has "number3" in title. If it does, return the index where number3 is found. Any suggestions?

2 Answers 2

5

Simple,

Approach 1:

if let indexOfItem = moreMenuItem.index(where: { (item) -> Bool in
        return item.title == "number3"
    }) {
        print("\(indexOfItem)")
    }
    else {
        print("item not found")
    }

Approach 2:

In case you dont want to compare simply a title string and rather want to compare two MoreMenuItem with based on their title, make MoreMenuItem confirm to Equatable protocol as shown below

class MoreMenuItem : Equatable {
    static func ==(lhs: MoreMenuItem, rhs: MoreMenuItem) -> Bool {
        return lhs.title == rhs.title
    }


    var title: String?
    var imageName: String?

    init(title: String, imageName: String) {
        self.title = title
        self.imageName = imageName }
}

Then use index(of:

let itemToCompare = MoreMenuItem(title: "number3", imageName: "email")
if let value = moreMenuItem.index(of: itemToCompare) {
        print("\(value)")
}

Hope its helpful :)

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

2 Comments

Nice! Works really well and the approach 2 is very helpful. Thanks!
Ops! Somehow I misclicked. Thanks again!
3

Try this one liner using index(where:) method.

if let index = moreMenuItem.index(where: { $0.title == "number3" }) {
    print(index)
}

1 Comment

Works perfectly! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.