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

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


当前回答

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的解决方案:

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

参考类型:

extension Array where Array.Element: AnyObject {

    func index(ofElement element: Element) -> Int? {
        for (currentIndex, currentElement) in self.enumerated() {
            if currentElement === element {
                return currentIndex
            }
        }
        return nil
    }
}

由于swift在某些方面比面向对象的函数性更强(数组是结构体,而不是对象),使用函数"find"对数组进行操作,返回一个可选值,所以准备好处理nil值:

let arr:Array = ["a","b","c"]
find(arr, "c")!              // 2
find(arr, "d")               // nil

使用firstIndex和lastIndex -这取决于你是在寻找项目的第一个索引还是最后一个索引:

let arr = ["a","b","c","a"]

let indexOfA = arr.firstIndex(of: "a") // 0
let indexOfB = arr.lastIndex(of: "a") // 3

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

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

对于SWIFT 3,您可以使用一个简单的函数

func find(objecToFind: String?) -> Int? {
   for i in 0...arrayName.count {
      if arrayName[i] == objectToFind {
         return i
      }
   }
return nil
}

这将给出数字的位置,所以你可以用like

arrayName.remove(at: (find(objecToFind))!)

希望对你有用