Swift: Arrays

Arrays in Swift:

Let’s begin with Arrays in Swift.

Array:

An array is a collection of values of the same data type that are stored in a specific order.

To create an empty array of a specific type, use the initializer syntax [Type]().

var age = [Int]()
 
// The array is empty: []

Initialize with Array Literal:

An array literal, which is a shorthand method of writing one or more values as an array collection, can use to initialize it.

A list of values separated by commas. It is surrounded by a pair of square brackets makes up an array literal.

// Using type inference:
var rainfall = [10.4, 11.5, 20.1, 10.9, 10.5]
 
// Being explicit with the type:
var temp: [Int] = [27, 29, 32, 19, 39]

Index:

The position of an item within an ordered list refers to as an index. To access a single element from an array, use the array[index] subscript notation.

Swift arrays are zero-indexed, which means the first element is at index 0.

var num = [2, 23, 1, 6, 9, 4]
 
print(num[0])  // Prints: 2
print(num[1])  // Prints: 23
print(num[2])  // Prints: 1
print(num[3])  // Prints: 6
print(num[4])  // Prints: 9
print(num[5])  // Prints: 4

.count Property:

The .count property returns the array’s total number of elements.


var num = [2, 5, 1, 22, 9, 3]
 
print(num.count)
 
// Prints: 6

.append() Method and += Operator:

The .append() can use to append a new item to the end of an array.

Use the += addition assignment operator to add elements from another array to an existing array.

var numArray = [1, 2]
 
numArray.append(3)
numArray += [4, 5]
 
// [1, 2, 3, 4, 5]

.insert() and .remove() Methods:

The .insert() can use to add an element to an array at a specific index. There are two main parameters: value and at: index.

On an array, the .remove() method can use to remove an element at a specific index. There is only one argument: at: index.

var vowels = ["e", "i", "o", "u", "y"]
 
vowels.insert("a", at: 0)
 
// ["a", "e", "i", "o", "u", "y"]
 
moon.remove(at: 5)
 
// ["a", "e", "i", "o", "u"]

Iterating Over an Array:

To iterate through the items in an array in Swift, use a forin loop.

This is a powerful tool for working with large amounts of data and modifying it.

var students = ["Dave", "Jake", "Lisa", "Lily", "Carlo"]
 
for person in students {
  print(person)
}
 
// Prints: Dave
// Prints: Jake
// Prints: Lisa
// Prints: Lily
// Prints: Carlo

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: