Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

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


                        }

                    })

                }
like image 592
Dominik Avatar asked Jul 06 '18 11:07

Dominik


4 Answers

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

like image 67
evasilis2000 Avatar answered Oct 03 '22 05:10

evasilis2000


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")
    }
}
like image 34
karjaubayev Avatar answered Oct 03 '22 07:10

karjaubayev


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
  }
}
like image 3
dr_barto Avatar answered Oct 03 '22 05:10

dr_barto


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
    }
}
like image 2
markturnip Avatar answered Oct 03 '22 07:10

markturnip