Home > OS >  how to access the next element in array without index running out of range?
how to access the next element in array without index running out of range?

Time:04-20

var a = [1,2,3,4,5]
 

for i in 0..<a.count {
    print(a[i 1])
}

// How can I make sure it doesn't run the for loop if the next element in the array // doesn't exist ?

CodePudding user response:

There are many ways. Which one you should take depends on your intent.

a.dropFirst().forEach {
  print($0)
}
import Algorithms

for pair in a.adjacentPairs() {
  print(pair.1)
}

https://github.com/apple/swift-algorithms/blob/main/Guides/AdjacentPairs.md

  • Related