How to find index of list item in Swift?

后端 未结 22 1573
离开以前
离开以前 2020-11-22 06:17

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 <

相关标签:
22条回答
  • 2020-11-22 06:28

    Swift 2.1

    var array = ["0","1","2","3"]
    
    if let index = array.indexOf("1") {
       array.removeAtIndex(index)
    }
    
    print(array) // ["0","2","3"]
    

    Swift 3

    var array = ["0","1","2","3"]
    
    if let index = array.index(of: "1") {
        array.remove(at: index)
    }
    array.remove(at: 1)
    
    0 讨论(0)
  • 2020-11-22 06:29

    in Swift 4.2

    .index(where:) was changed to .firstIndex(where:)

    array.firstIndex(where: {$0 == "person1"})
    
    0 讨论(0)
  • 2020-11-22 06:29

    You can also use the functional library Dollar to do an indexOf on an array as such http://www.dollarswift.org/#indexof-indexof

    $.indexOf([1, 2, 3, 1, 2, 3], value: 2) 
    => 1
    
    0 讨论(0)
  • 2020-11-22 06:30

    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")
        }
    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
    
    0 讨论(0)
  • 2020-11-22 06:30

    Any of this solution works for me

    This the solution i have for 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
            })
    
    0 讨论(0)
  • 2020-11-22 06:32

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题