Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift array slicing with a range in the subscript

Tags:

swift

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?

like image 977
Alex Wayne Avatar asked Aug 03 '14 21:08

Alex Wayne


1 Answers

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.)

like image 136
jtbandes Avatar answered Oct 15 '22 03:10

jtbandes