斯威夫特我如何检查我是否遍历List [String]的最后一项

Dom*_*nik 7 ios swift

我需要检查何时遍历最后一个项目。我不能只在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


                        }

                    })

                }
Run Code Online (Sandbox Code Playgroud)

kar*_*yev 17

如果你不想使用索引,你可以像这样检查元素:

for element in array {
    if element == array.first {
        print("first")
    } else if element == array.last {
        print("last")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您知道数组中的每个元素都是唯一的,则此方法有效。如果存在重复值的可能性,那么您应该使用索引方法。 (3认同)

小智 12

dr_barto的答案将起作用,但需要进行以下修改:

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

从Apple文档中:

endIndex是数组的“过去”位置,即比最后一个有效的下标参数大一个的位置