Loop through a range of an Array

Viewed 2428

How can I loop through an array range? Example if I had 5 objects in an array. I want to loop from index [3] to end of the array in this example it would go through and update objects 3-5 and skip objects 1 & 2. This is what I have so far using the stride method(this code isn't working). Is this the correct method? How can I achieve this?

stride(from: markers[index], to: markers.endIndex, by: 1).forEach { i in
    // Do something for each array object
}
3 Answers

You can use the range operator to get sequences of indices or slices of the array. Which you use depends on what you are trying to do. For clarity I am going to leave out error checking.

For example:

let letters = ["a", "b", "c", "d", "e"]
letters[3...].forEach { print($0) } // prints d e 

// or you can print up to index 3
letters[...3].forEach { print($0) } // prints a b c d

// or print elements 1-3 inclusive
letters[1...3].forEach { print($0) } // prints b c d 

// or print elements 1-3 excluding index 3
letters[1..<3].forEach { print($0) } // prints b c d 

If you wanted to modify the elements of the array you pass in the indices rather than the elements

var mutableLetters = ["a","b","c","d","e"]
(3..<mutableLetters.count).forEach {
    mutableLetters[$0] = mutableLetters[$0].uppercased()
}

notice here we need to specify both limits because the range knows nothing about the array.

It's often more Swifty not to modify things in place so, if this fits your use case you might consider something like this:

let immutableLetters = ["a","b","c","d","e"]
let upperCasedFromThreeOn = immutableLetters[3...].map { $0.uppercased() }
// upperCasedFromThreeOn = ["D","E"]

As a final note, sometimes you need to know both the index and the element. You can use a forEach on the indices as above, but another way is to use enumerated() this creates a tuple of the index and element.

let range = 2...4
immutableLetters.enumerated()
    .filter { (index,_) in range.contains(index) }
    .forEach { (index, element) in
        print("\(index) \(element)")
    }

Here I've used a filter after the enumeration so that the indices match the original array.

You can simply iterate over your array slice dropping the first n elements:

let markers = ["a","b","c","d","e"]

for marker in markers.dropFirst(2) {
    print(marker)   // this will print 'c d e'
}

If you need to change your array you can iterate over a slice of its indices:

let markers = ["a","b","c","d","e"]

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

You can simply loop through the array using Range Operator in Swift like,

var markers = ["M1","M2","M3","M4","M5"]
let count = markers.count
if count > 2 {
    for i in 2..<count {
        //add your code here..
    }
}

In the above code, I've used half-open range operator(..<)

Related