Accessing Array Elements

You can access elements from an array by using what Swift calls subscripts. You will learn much more about subscripting later, but for now, you just need to know that you can use the square brackets notation that you see in many other languages to access elements of an array. Here’s an example:

var myArray = [1,2,3,4]myArray[0] // 1

Arrays start from an index of 0. Grabbing the 0th element will give you back the first element. You can also use the startIndex property of the array to find this out. You can also grab the total number of items in an array by using the count method:

myArray.count  // 4

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.