Status of Slice in Swift
So yes…. by now I do have 5 years of Swift experience, but recently I’m trying to re-educate myself due to changes made by Apple. Because I’m digging into recently, I may post here sometimes about it.
slice — to cut something with a sharp object (such as a knife).
definition of “slice” word correspond to Slice struct in Swift. Slice in Swift is a part of sequence (collection), just a slice of something.
Struct Slice is defined like this:
as you can see, the there are subscripts with given range, that return a slice of data.
Slice type is defined as collection type struct, in addition there is ArraySlice struct that is very similar to Array — there are more similarities between these two.
so I can consider Slice (especially ArraySlice) as Array for special needs.
How it works
a slice of array if referenced and stored in Slice value, although when I modify original array, slice won’t change.
if a Slice instance is wrapped around a mutable collection that has value semantics (for example, Array), mutating the original collection would not affect the copy stored inside of the slice.
as a result array is [1, 3, 3, 4, 5] and subslice is [2, 3, 4]
Slice is widely used across Standard Library, though it’s generalised as SubSequence (A type that represents a subsequence of some of the elements)
I found it in functions like: prefix(), suffix(), split(). Personally I like split(), let’s take a look how to deal with it: (of course type definition can be ommited, but I addedd it for readability)
in this example, given array [1, 2, 3, 4, 5] is splitted into two chunks: [1, 2] and [4, 5] because value 3 is consider as separator. As a result I got:
var splitted:[ArraySlice<Int>] = [[1,2][4,5]]
it’s an Array with two slices, that’s how it’s defined for Array. For String it would be array of String.
While ArraySlice is a kind of collection (sequence) for special needs, Slice struct doesn’t mean that result is of type Slice<T> (subrange of String is still String). I should not expect that result of slice is the same type as sliced collection.
PS. many things was changed between 1.0 and 2.1 in terms of Slice — this text has been updated to Swift 2.1