Start learning free

LESSON 95 OF 349 · ARRAYS I

Array Count in Swift in Swift

Lesson

We can get the count of an array using the .count property:

var ourArray = [50, 40, 30]

// Printing the count:
print(ourArray.count) // Output: 3

// Changing the array:
ourArray.remove(at: 2)

// Printing the new count:
print(ourArray.count) // Output: 2

Using the count

We can use the count to access items from the end of an array.

Because arrays are 0-indexed, the index of the last item is count - 1:

var ourArray = [50, 40, 30]

let count = ourArray.count

// Printing the last item:
print(ourArray[count - 1]) // Output: 30

// Printing the second to last item:
print(ourArray[count - 2]) // Output: 40

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    Array Length in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free