Working With Rotate
The new Rotate feature let you rotate a collection by specifying which index to move to the beginning. To understand it, try it out and observe how the collection changes.
Add the following code to the Rotate playground page:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.rotate(toStartAt: 3)
print(numbers) // [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
With a collection of numbers from one to ten, calling rotate(toStartAt:)
on the collection shift all elements to the left until the first element is the one at the index specified by the parameter. This algorithm is done in iterations which move the first item from the beginning to the end and shift all the rest to the left. The method returns the index of where the item that was first in the original collection is in the final, rotated collection. So in this example, the element "1" that was in index 0 is now in index 7.
When you rotate the entire collection, the number of elements in the collection minus the value you provide in toStartAt will be the expected index location of the first element before the rotation happens. And if you rotate by that number again, you'll return the collection to its original state:
numbers.rotate(toStartAt: 7) // returned back to normal
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
An alternative method lets you rotate a specific part of the collection. Say you want to rotate the first half of the collection and leave the second half untouched:
numbers.rotate(subrange: 0..<5, toStartAt: 2)
print(numbers) // [3, 4, 5, 1, 2, 6, 7, 8, 9, 10]
This will rotate the elements from one to five and leave the elements from six to ten untouched.
Where to Go From Here?
Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.
In this tutorial, you learned about the many algorithms in the open-source Swift Algorithms package and what they do. You saw that Swift Algorithms makes use of lazy collections to ensure computation is only done when needed. And you learned how to put the algorithms into practice.
You can learn more about this package by reading Apple's documentation.
You can also check out the Swift Evolution proposal for this package.
Finally, it's worth looking into the Swift Numerics Package, which provides Swift data structures for complex numbers and many other math related additions.
We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!