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

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


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
  }
}

Tags:

Ios

Swift