Arrays are (also) structs in Swift. What does that mean in practice?
Prerequisites
Please make sure you watch first the following prerequisite videos:
Did you know that arrays are also structs under the hood? What does that mean in practice?
It means that arrays are more than just a simple collection of elements. They come out of the box with properties and functions, just like any other struct. And more than that, we can extend their functionality by adding extensions to arrays, if we want to.
Last time we learned that arrays are un-keyed multi-value collections of elements, all under a single name. Individual elements can be accessed by an index indicating the position in the array.
Being structs under the hood, arrays come with some predefined properties. One property that we tend to use often is count, which returns the size of the array. Another good property is called isEmpty, which returns a boolean, telling us whether the array is empty or not.
There is also a property called first, which returns the very first element in the array, if it exists. This will be an optional value, because there are cases when the array is empty and this first element does not exist.
Similarly, there is a last property, which returns, well, you get the point. How about functions? The function randomElement() will return some element at random, and of course, the return value will also be optional, to cover cases when the array is empty.
The function contains() returns a boolean, indicating whether the array contains a specific element or not.
And the function shuffle() will reorder the array at random, a good function for a card game. There are a few more properties and functions, of course, but I will stop with these small examples for now.
And there you have it: arrays are structs under the hood, providing more than just access to elements. Properties like count, isEmpty, first, last, and functions like randomElement() and shuffle() are just a few good examples. Consult the Apple documentation to learn more.