简体   繁体   中英

Get index from a model array in 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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM