How to find index of list item in Swift?

2018-12-31 09:31发布

I am trying to find an item index by searching a list. Does anybody know how to do that?

I see there is list.StartIndex and list.EndIndex but I want something like python's list.index("text").

标签: arrays swift
17条回答
高级女魔头
2楼-- · 2018-12-31 10:14

For custom class, you need to implement the Equatable protocol.

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)
查看更多
裙下三千臣
3楼-- · 2018-12-31 10:17

For SWIFT 3 you can use a simple function

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

This will give the number position, so you can use like

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

Hope to be useful

查看更多
浮光初槿花落
4楼-- · 2018-12-31 10:17

Swift 4

For reference types:

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
    }
}
查看更多
公子世无双
5楼-- · 2018-12-31 10:18

Swift 4. If your array contains elements of type [String: AnyObject]. So to find the index of element use the below code

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)

Or If you want to found index on the basis of key from Dictionary. Here array contains Objects of Model class and I am matching id property.

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")
}
查看更多
大哥的爱人
6楼-- · 2018-12-31 10:21

I think it's worth mentioning that with reference types (class) you might want to perform an identity comparison, in which case you just need to use the === identity operator in the predicate closure:


Swift 4 / Swift 3:

let person1 = Person(name: "John")
let person2 = Person(name: "Sue")
let person3 = Person(name: "Maria")
let person4 = Person(name: "Loner")

let people = [person1, person2, person3]

let indexOfPerson1 = people.index{$0 === person1} // 0
let indexOfPerson2 = people.index{$0 === person2} // 1
let indexOfPerson3 = people.index{$0 === person3} // 2
let indexOfPerson4 = people.index{$0 === person4} // nil

Note that the above syntax uses trailing closures syntax, and is equivalent to:

let indexOfPerson1 = people.index(where: {$0 === person1})


Swift 2 - the index function syntax used to be:

let indexOfPerson1 = people.indexOf{$0 === person1}


* Note the relevant and useful comment by paulbailey about class types that implement Equatable, where you need to consider whether you should be comparing using === (identity operator) or == (equality operator). If you decide to match using ==, then you can simply use the method suggested by others (people.index(of: person1)).

查看更多
初与友歌
7楼-- · 2018-12-31 10:21

SWIFT 4

Let's say you want to store a number from the array called cardButtons into cardNumber, you can do it this way:

let cardNumber = cardButtons.index(of: sender)

sender is the name of your button

查看更多
登录 后发表回答