Status of Slice in Swift

https://twitter.com/krzyzanowskim/status/487880729502941184

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:

https://gist.github.com/krzyzanowskim/b630461715e7422c9a78

as you can see, the there are subscripts with given range, that return a slice of data.

Slice type

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.

https://gist.github.com/krzyzanowskim/48f1f6c2fdb80be7911d

so I can consider Slice (especially ArraySlice) as Array for special needs.

How it works

https://gist.github.com/krzyzanowskim/e049b278c9e84639fe22

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.
https://gist.github.com/krzyzanowskim/b9a369c2b1ef4f5b197f

as a result array is [1, 3, 3, 4, 5] and subslice is [2, 3, 4]

Where?

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)

https://gist.github.com/krzyzanowskim/db156bc6853106055c4b

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.

Conclusion

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

@krzyzanowskim

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.