What is the expected result of subscribing to a range?

I cannot find any documentation explaining what the subtype should do. I expect this to give the nth value of the range, but it seems to return the indexed value itself.

let range = 10...20
let valueFromRange = range[2]

In this case, I expect it to valueFromRangebe equal 12, but it will be equal 2. This is similar to all ranges (or at least all ranges of types Range<Int>and Range<Double>).

Is this the value I should get? Also, to ignore what I think is probably the most commonly expected behavior, this behavior is also useless.

+4
source share
3 answers

Array, :

let range = Array(10..20)
range[2] // returns 12

range.startIndex , strided :

let range = (10..20).by(3)
range[2] // error: 'StridedRangeGenerator<Int>' does not have a member named 'subscript'
+1

n- - range.startIndex + n. , , :

let valueFromRange = range[range.startIndex+2]

range[12]

, n- n, :

let rangeConverted = Array(range)
rangeConverted[2] // will return 12
0

, range[subscript], , . , , , :

class Range {
  var _startIndex
  var _endIndex
}

Now I'm not sure if there can be ranges without a number. If not, then the index is indeed a value. So basically 10..20means that the range starts at 10 and ends at 20. I assume for the for loop

for i in 10..20 {}

coincides with

for i = _startIndex; i < _endIndex; i++

So, perhaps the range does not support the index, and this is just some inherited index from some base class.

Again, no solid evidence, and I really don't find the doc for Range in any link. I also think that it would be nice to maintain the index, but only my 2c.

0
source

Source: https://habr.com/ru/post/1543762/


All Articles