3

I am a beginner of Swift for iOS development, and want to find an elegant way to loop through an array from the second element.

If it is in Objective-C, I think I can write the code like below.

if(int i = 1; i < array.count; i++){
    array[i].blablabla....
}

And I have tried several methods to do this in swift

for i in  1..<array.count {
    array[i].blablabla....
}

But in this way, if the array's count is zero, the app will crash, because it cannot create an array from 1 to 0.

I also tried code like this, but it seems that it cannot enumerate from the second element.

for (index, object) in array.enumerate() {
    object.blablabla...
}

So what's the best way to do this, do you guys have any idea?

5 Answers 5

15

You can use your array indices combined with dropfirst:

let array = [1,2,3,4,5]

for index in array.indices.dropFirst() {
    print(array[index])
}

or simply:

for element in array.dropFirst() {
    print(element)
}
Sign up to request clarification or add additional context in comments.

Comments

1

you can also use custom subscript to make sure you avoid crashing

extension Array {
    subscript (gurd index: Index) -> Array.Element? {
        return (index < self.count && index >= 0) ? self[index] : nil
    }
}

use example:

let myarray = ["a","b","c","d","e","f","g","h"]

 for i in -15...myarray.count+20{
            print(myarray[gurd: i])
        }

3 Comments

How does this solve the question about "loop through an array from the second element" ?
quote : "But in this way, if the array's count is zero, the app will crash, because it cannot create an array from 1 to 0."
OK, I see what you mean.
1

In general, there is a nice pattern for getting a sub-array like this:

let array = [1, 2, 3, 4, 5]
array[2..<array.count].forEach {
    print($0)     // Prints 3, 4, 5 (array from index 2 to index count-1)
}

Leo's answer is more succinct and a better approach for the case you asked about (starting with the second element). This example starts with the third element and just shows a more general pattern for getting arbitrary ranges of elements from an array and performing an operation on them.

However, you still need to explicitly check to make sure you are using a valid range to avoid crashing as you noted, e.g.:

if array.count > 1 {
    array[2..<array.count].forEach {
        print($0)
    }
}

8 Comments

array.dropFirst().forEach { }
@LeoDabus Yep, that's good for this specific case, and I saw it in your answer. I'm just noting an additional way to get a range of elements from an array that can start and end with any index. Works for this case (though more verbose than your approach) but also for many other cases
array.count > 2 , that means that the array should have at least 3 elements.. so if the array had only 2, you would still be able to get the element at position 1 but the condition would prevent the loop from running
Btw array indices starts from 0, so if your index starts at 2 you would be starting from the third element
@LeoDabus Yes, that's why the comment says it would print 3, 4, 5 and not 2, 3, 4, 5. I'm showing a general approach, not just starting from the second element, which your answer is better for. I noted in my answer more clearly that it's a general purpose approach, not a better alternative for getting the second element onward
|
0
  if array.count>=2 {
     for n in 1...array.count-1{
         print(array[n])   //will print from second element forward 
      }
 }

Comments

-1

You could use array.dropFirts(), but if you need to iterate starting from 2nd element or 3rd I would do something like this:

for (index, item) in array.enumerated() where index > 1 {
    item.blablabla()
}

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.