从Swift中的模型数组中获取索引

时间:2018-01-09 08:23:34

标签: ios arrays swift

我有一个像这样的自定义数组

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

这是我的模型类

class MoreMenuItem {

    var title: String?
    var imageName: String?

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

现在让我说我有一个字符串“number3”,我想检查我的数组是否在标题中有“number3”。如果是,则返回找到number3的索引。有什么建议吗?

2 个答案:

答案 0 :(得分:4)

简单,

方法1:

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

方法2:

如果您不想简单地比较标题字符串,而是希望根据标题比较两个MoreMenuItem,请MoreMenuItem确认Equatable协议,如下所示

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 }
}

然后使用index(of:

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

希望它有用:)

答案 1 :(得分:2)

使用index(where:)方法试用这个衬垫。

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