Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index from a model array in Swift

Tags:

arrays

ios

swift

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?


1 Answers

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 :)

like image 193
Sandeep Bhandari Avatar answered Dec 15 '25 14:12

Sandeep Bhandari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!