What's going on here?
var foo: [UInt8] = [1,2,3,4]
var bar: [UInt8] = foo[1...2] // 'Range<Pos>' is not convertible to 'Int'
But this compiles fine:
var foo: [UInt8] = [1,2,3,4]
var bar = foo[1...2]
The docs only explicitly mention this in terms of replacement:
shoppingList[4...6] = ["Bananas", "Apples"]
So what exactly does Array[Range]
return then? And what's the simplest way to fetch objects between two array indices?
struct Array
declares subscript (subRange: Range<Int>) -> Slice<T>
. Therefore, bar
's type should be Slice<UInt8>
, not [UInt8]
. Slice
conforms to the same protocols as Array
, so the rest of your code won't need to change, and you can choose to just leave off the type annotation. (Or, you could use Array(foo[1...2])
to convert it to an array if you really want to.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With