How to find index of list item in Swift?

后端 未结 22 1958
离开以前
离开以前 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: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
    

提交回复
热议问题