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
}
})
}
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
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")
}
}
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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With