我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?

我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。


当前回答

你可以用闭包来过滤数组:

var myList = [1, 2, 3, 4]
var filtered = myList.filter { $0 == 3 }  // <= returns [3]

你可以对数组进行计数:

filtered.count // <= returns 1

所以你可以通过组合这些来确定数组是否包含你的元素:

myList.filter { $0 == 3 }.count > 0  // <= returns true if the array includes 3

如果你想找这个职位,我不认为有什么花哨的方法,但你可以这样做:

var found: Int?  // <= will hold the index if it was found, or else will be nil
for i in (0..x.count) {
    if x[i] == 3 {
        found = i
    }
}

EDIT

当我们这样做的时候,为了一个有趣的练习,让我们扩展Array来有一个find方法:

extension Array {
    func find(includedElement: T -> Bool) -> Int? {
        for (idx, element) in enumerate(self) {
            if includedElement(element) {
                return idx
            }
        }
        return nil
    }
}

现在我们可以这样做:

myList.find { $0 == 3 }
// returns the index position of 3 or nil if not found

其他回答

斯威夫特4。如果数组包含类型为[String: AnyObject]的元素。因此,要查找元素的索引,请使用下面的代码

var array = [[String: AnyObject]]()// Save your data in array
let objectAtZero = array[0] // get first object
let index = (self.array as NSArray).index(of: objectAtZero)

或者如果你想找到索引的基础上的关键字从字典。这里数组包含对象的模型类和我匹配id属性。

   let userId = 20
    if let index = array.index(where: { (dict) -> Bool in
           return dict.id == userId // Will found index of matched id
    }) {
    print("Index found")
    }
OR
      let storeId = Int(surveyCurrent.store_id) // Accessing model key value
      indexArrUpTo = self.arrEarnUpTo.index { Int($0.store_id) == storeId }! // Array contains models and finding specific one

您还可以使用函数库Dollar在数组上执行indexOf,例如http://www.dollarswift.org/#indexof-indexof

$.indexOf([1, 2, 3, 1, 2, 3], value: 2) 
=> 1

For (>= swift 4.0)

这相当简单。 考虑下面的Array对象。

var names: [String] = ["jack", "rose", "jill"]

为了得到元素rose的索引,你所要做的就是:

names.index(of: "rose") // returns 1

注意:

Array.index(of:)返回一个可选值<Int值>。 Nil表示元素不存在于数组中。 您可能希望强制打开返回值,或者使用if-let来绕过可选选项。

在Swift 4/5中,使用“firstIndex”查找索引。

let index = array.firstIndex{$0 == value}

对于自定义类,您需要实现Equatable协议。

import Foundation

func ==(l: MyClass, r: MyClass) -> Bool {
  return l.id == r.id
}

class MyClass: Equtable {
    init(id: String) {
        self.msgID = id
    }

    let msgID: String
}

let item = MyClass(3)
let itemList = [MyClass(1), MyClass(2), item]
let idx = itemList.indexOf(item)

printl(idx)