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

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


当前回答

在Swift 4中,如果你正在遍历你的DataModel数组,确保你的数据模型符合Equatable Protocol,实现lhs=rhs方法,只有这样你才能使用”。指数(“。例如

class Photo : Equatable{
    var imageURL: URL?
    init(imageURL: URL){
        self.imageURL = imageURL
    }

    static func == (lhs: Photo, rhs: Photo) -> Bool{
        return lhs.imageURL == rhs.imageURL
    }
}

然后,

let index = self.photos.index(of: aPhoto)

其他回答

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

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

在Swift 2 (Xcode 7)中,Array包含了一个由CollectionType协议提供的indexOf方法。(实际上,有两个indexOf方法——一个使用相等来匹配参数,另一个使用闭包。)

在Swift 2之前,泛型类型(如集合)无法为从它们派生的具体类型(如数组)提供方法。所以,在Swift 1中。X, index of是一个全局函数…它也被重新命名了,所以在Swift 1中。X,这个全局函数叫做find。

这也是可能的(但不是必要的)使用indexOfObject方法从NSArray…或者其他任何来自基金会的更复杂的搜索方法,这些方法在Swift标准库中没有等价物。只需导入Foundation(或另一个传递导入Foundation的模块),将数组转换为NSArray,就可以使用NSArray上的许多搜索方法。

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来绕过可选选项。

斯威夫特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

虽然indexOf()工作得很好,但它只返回一个索引。

我正在寻找一种优雅的方法来获得满足某些条件的元素的索引数组。

以下是如何做到这一点:

斯威夫特3:

let array = ["apple", "dog", "log"]

let indexes = array.enumerated().filter {
    $0.element.contains("og")
    }.map{$0.offset}

print(indexes)

斯威夫特2:

let array = ["apple", "dog", "log"]

let indexes = array.enumerate().filter {
    $0.element.containsString("og")
    }.map{$0.index}

print(indexes)