0

So lets say we have an array a = [20,50,100,200,500,1000]

Generally speaking we could do for number in a { print(a) } if we wanted to check the entirety of a.

How can you limit what indexes are checked? As in have a set beginning and end index (b, and e respectively), and limit the values of number that are checked to between b and e?

For an example, in a, if b is set to 1, and e is set to 4, then only a1 through a[4] are checked.

I tried doing for number in a[b...e] { print(number) }, I also saw here someone do this, for j in 0..<n { x[i] = x[j]}, which works if we want just a ending.

This makes me think I can do something like for number in b..<=e { print(a[number]) } Is this correct?

I'm practicing data structures in Swift and this is one of the things I've been struggling with. Would really appreciate an explanation!

2 Answers2

1

Using b..<=e is not the correct syntax. You need to use Closed Range Operator ... instead, i.e.

for number in b...e {
    print(a[number])
}

And since you've already tried

for number in a[b...e] {
    print(number)
}

There is nothing wrong with the above syntax as well. You can use it either way.

PGDev
  • 23,751
  • 6
  • 34
  • 88
0

An array has a subscript that accepts a Range: array[range] and returns a sub-array.

A range of integers can be defined as either b...e or b..<e (There are other ways as well), but not b..<=e

A range itself is a sequence (something that supports a for-in loop)

So you can either do

for index in b...e {
    print(a[index])
}

or

for number in a[b...e] {
    print(number)
}

In both cases, it is on you to ensure that b...e are valid indices into the array.

RookiePro
  • 633
  • 1
  • 9
  • 18