我需要检查何时遍历最后一个项目。我不能只在for循环后放置该行,因为这样我总是收到一个空列表。我尝试了以下方法,但此方法不起作用:
.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
}
})
}
答案 0 :(得分:4)
dr_barto的答案会起作用,但需要进行以下修改:
for (idx, element) in array.enumerated() {
if idx == array.endIndex-1 {
// handling the last element
}
}
从Apple文档中获取:
endIndex是数组的“末尾”位置,即比最后一个有效的下标参数大一个的位置。
答案 1 :(得分:3)
如果你不想使用索引,你可以像这样检查元素:
for element in array {
if element == array.first {
print("first")
} else if element == array.last {
print("last")
}
}
答案 2 :(得分:1)
正如评论中指出的那样,您应该使用enumerated
;给定array
,您将像这样使用它:
for (idx, element) in array.enumerated() {
if idx == array.endIndex {
// handling the last element
}
}
答案 3 :(得分:0)
对于像我这样的 swift 新手.. 我附上了完整的代码。
ref.child("BookShelf").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
if let datasnap = snapshot.value as? Dictionary<String, Any> {
for (index,data) in datasnap.enumerated() {
let book = Book(userid: data.key , dataSnap: data.value as! Dictionary<String, Any>)
bookShelf.append(book)
print("index",index)
print("datasnap.count-1",datasnap.count-1)
if(index == datasnap.count-1){
print("1 bookshelf count getFirebaseData()",bookShelf.count)
self.showDashBoard(bookShelf: bookShelf)
}
}
//if last data then trigger show
}
}) { (error) in
print(error.localizedDescription)
}
答案 4 :(得分:0)
也可以做成扩展:
extension Array {
func lastIndex(index: Int) -> Bool {
index == endIndex-1
}
}
或
extension Array where Element : Equatable {
func isLast(element: Element) -> Bool {
last == element
}
}
答案 5 :(得分:-1)
尝试此解决方案
.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
for (index,rest) in snapshot.children.allObjects {
if index == (snapshot.children.allObjects.count - 1){
//yeah finally you are getting the last object :)
}
}
})
}
P.S:我假设snapshot.children.allObjects是[DataSnapshot]的数组