What is a slice in Swift?

hjing picture hjing · Jun 6, 2014 · Viewed 38.1k times · Source

What is a slice in Swift and how does it differ from an array?

From the documentation, the type signature of subscript(Range) is:

subscript(Range<Int>) -> Slice<T>

Why not return another Array<T> rather than a Slice<T>?

It looks like I can concatenate a slice with an array:

var list = ["hello", "world"]
var slice: Array<String> = [] + list[0..list.count]

But this yields the error:

could not find an overload for 'subscript' that accepts the supplied arguments

var list = ["hello", "world"]
var slice: Array<String> = list[0..list.count]

What is a slice?

Answer

matt picture matt · Jun 6, 2014

The slice points into the array. No point making another array when the array already exists and the slice can just describe the desired part of it.

The addition causes implicit coercion, so it works. To make your assignment work, you would need to coerce:

var list = ["hello", "world"]
var slice: Array<String> = Array(list[0..<list.count])