Swift how can i check if i iterate through the last item of List[String]

18,191

Solution 1

The answer of dr_barto will work but needs the following adaptation:

    for (idx, element) in array.enumerated() {
      if idx == array.endIndex-1 {
        // handling the last element
       }
     }

From the Apple documentation:

endIndex is the array’s “past the end” position—that is, the position one greater than the last valid subscript argument

Solution 2

If you don't want to use index, you can check element like this:

for element in array {
    if element == array.first {
        print("first")
    } else if element == array.last {
        print("last")
    }
}

Solution 3

EDIT my answer won't work since (as pointed out in the comments) endIndex is never going to match any index value returned from enumerated because it denotes the index after the last element. See https://stackoverflow.com/a/53341276/5471218 for how it's done correctly :)


As pointed out in the comments, you should use enumerated; given an array, you'd use it like this:

for (idx, element) in array.enumerated() {
  if idx == array.endIndex {
    // handling the last element
  }
}

Solution 4

Could be made into an extension also:

extension Array {
    func lastIndex(index: Int) -> Bool {
        index == endIndex-1
    }
}

or

extension Array where Element : Equatable {
    func isLast(element: Element) -> Bool {
        last == element
    }
}
Share:
18,191

Related videos on Youtube

Dominik
Author by

Dominik

Updated on June 15, 2022

Comments

  • Dominik
    Dominik almost 2 years

    i need to check when i iterated through the last item. I cannot just put the line after my for loop because then i receive always an empty list. I tried the following but this one doesnt work:

       .observeSingleEvent(of: .value, with: { (snapshot) in
                if snapshot.exists(){
    
                    for rest in snapshot.children.allObjects.count as! [DataSnapshot] {
                        let refi = Database.database().reference().child("Users")
                        refi.observeSingleEvent(of: .value, with: { (snapshoti) in
                            if snapshoti.value as! String == "active"{
    
                                let userid = rest.key
                                self.someProtocol[rest.key] = self.checksum
    
                                if self.checksum == self.someProtocol.count-1 {
                                    self.sortUsers()
                                }else{
    
                                }
                                self.checksum = self.checksum+1
    
    
                            }
    
                        })
    
                    }
    
    • Pravin Tate
      Pravin Tate almost 6 years
      use enumerate for iteration and from that you can check index == array.lastIndex
    • dr_barto
      dr_barto almost 6 years
      The line snapshot.children.allObjects.count as! [DataSnapshot] looks suspicious: is count really returning an array or DataSnapshot?
    • Dominik
      Dominik almost 6 years
      @PravinTate could you describe it more in detail.
    • Dominik
      Dominik almost 6 years
      @dr_barto sorry i changed this line into snapshot.children.allObjects as! [DataSnapshot] but doesnt work
    • dr_barto
      dr_barto almost 6 years
      Are you getting a compiler error, a runtime error, or is the code just not doing what you want it to do? Please be more specific and post error messages.
    • Dominik
      Dominik almost 6 years
      it just dont do what i want
    • Dominik
      Dominik almost 6 years
      i just need to know when the last item of the snapshot.children loop is reached
  • Dominik
    Dominik almost 6 years
    but how can i use it while iterating through my Datasnapshot?
  • dr_barto
    dr_barto almost 6 years
    Just set array to your list-of-whatever; in your case this might be snapshot.children.allObjects as! [DataSnapshot].
  • Dominik
    Dominik almost 6 years
    but for snapshot i cannot add enumerated()
  • dr_barto
    dr_barto almost 6 years
    let array = snapshot.children.allObjects as! [DataSnapshot], then you can call array.enumerated
  • Dominik
    Dominik almost 6 years
    Datasnapshot has no member lastIndex
  • dr_barto
    dr_barto almost 6 years
    You are right, sorry :) c&p error from the other comment, it's endIndex; I'll update the example accordingly.
  • dr_barto
    dr_barto almost 6 years
    What's not working? I updated the example code, have you tried it in your code?
  • Matias Pequeno
    Matias Pequeno over 4 years
    In your example, idx can never be equals to endIndex since endIndex is the index following the last index of a collection. endIndex is analogous to the amount of items in a collection.
  • dr_barto
    dr_barto over 4 years
    @MatiasPequeno right, has been corrected here: stackoverflow.com/a/53341276/5471218