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

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


当前回答

斯威夫特2.1

var array = ["0","1","2","3"]

if let index = array.indexOf("1") {
   array.removeAtIndex(index)
}

print(array) // ["0","2","3"]

斯威夫特3

var array = ["0","1","2","3"]

if let index = array.index(of: "1") {
    array.remove(at: index)
}
array.remove(at: 1)

其他回答

对于自定义类,您需要实现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)

这些方法对我都适用

这是我对Swift 4的解决方案:

let monday = Day(name: "M")
let tuesday = Day(name: "T")
let friday = Day(name: "F")

let days = [monday, tuesday, friday]

let index = days.index(where: { 
            //important to test with === to be sure it's the same object reference
            $0 === tuesday
        })

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

斯威夫特4

假设你想从名为cardButtons的数组中存储一个数字到cardNumber中,你可以这样做:

let cardNumber = cardButtons.index(of: sender)

Sender是按钮的名称

在Swift 4.2中

.index(where:)被更改为.firstIndex(where:)

array.firstIndex(where: {$0 == "person1"})