Slice that Collection: A Swift guide

What are slices, and how are they used?

Prerequisites:

  • Some knowledge of Collections in Swift

Terminology

Array: An ordered series of objects which are the same type

Collections

In Swift, collections (as in other languages) are vitally important. ArraySlices provide a view on an array rather than a new array, meaning that both the initial array and the slice share the same indicies.

The Array Summary

If we have an ages array

let ages = [1,5,12,15,2,26,67,36]
let sliceOfAges = ages[1...2]
sliceOfAges[0] // EXC_BAD_INSTRUCTION out of bounds

The Set Summary

For a set we can have the same ages data, but of course the result will be unordered.

let agesSet = [1,5,12,15,2,26,67,36]
let sliceOfAgesSet = agesSet.dropLast()

The Dictionary Summary

For a dictionary things are rather familiar after the initilization step

let agesDict : [Int: Int] = [0:1, 1:5, 2:12, 3:15, 4:2, 5:26, 6:67, 7:26]
let sliceOfDict = agesDict.dropLast()

Conclusion:

ArraySlices are useful, and actually are incredibly similar to Slice which applies to any collection. If you are interested in this wider struct please do read on in my accompanying article on arrayslices. The article? It’s HERE.

Extend your knowledge

  • Apple have a subscript guide (HERE)

The Twitter contact:

Any questions? You can get in touch with me HERE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store