Swift: Index

Index in Swift:

How do we get an individual value now that we have an array? Here’s where index comes in handy in Swift.

The position of an item within an ordered list is referred to as an index. In Swift, arrays are zero-indexed, which means that the first item has index 0, the second item has index 1, and so on.

Assume we have a String array containing consonants:

var consonants = ["b", "c", "d", "f", "g"];
  • The item at index 0 is "b".
  • The item at index 1 is "c".
  • The item at index 2 is "d".
  • The item at index 3 is "f".
  • The item at index 4 is "g".

We can use the array[index] subscript syntax to retrieve individual elements. It uses square brackets, [] around an index value.

For example:

print(consonants[0]);     // Prints: b
print(consonants[1]);     // Prints: c
print(consonants[2]);     // Prints: d
print(consonants[3]);     // Prints: f
print(consonants[4]);     // Prints: g

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: