Manipulating Arrays - Adding and Removing Elements

Dive Into Array Manipulation

Welcome back! In our previous lesson, we learned how to manage ordered data using arrays. Now that you're familiar with creating and accessing arrays, let's take it a step further. Today, we'll focus on manipulating arrays by adding and removing elements. This skill is essential for managing dynamic data, like updating a list of planets for a space mission.

What You'll Learn

In this lesson, you will build on your array knowledge by:

  1. Adding elements: Learn how to append new items to the end of an array.
  2. Removing elements: Discover how to remove the last item from an array.
  3. Concatenating arrays: Learn how to join two arrays together.
  4. Creating multi-type arrays: Understand how to create arrays that can hold elements of multiple data types.

Adding and Removing Elements

Adding elements to an array allows you to dynamically expand your data collection. You can append individual elements using the append method. Removing elements is equally crucial for managing your data. The removeLast() method allows you to delete the last item of an array, ensuring your data is up-to-date.

Here's an example:

var planets: [String] = ["Mercury", "Venus", "Earth", "Mars", "Jupiter"]

// Add a new element at the end of the array
planets.append("Saturn")
print(planets) // ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn"]

// Remove the last element of the array
let lastPlanet = planets.removeLast()
print("The last planet was: \(lastPlanet)") // The last planet was: Saturn

Concatenating Arrays and Creating Multi-Type Arrays

You can concatenate two arrays using the append(contentsOf:) method. Additionally, to create an array that can hold elements of multiple data types, you define the array with the type Any. This allows the array to store elements of different types like integers, strings, and doubles.

Here's an example:

var primeNumbers: [Any] = [2, 3, 5]
print("Array1: \(primeNumbers)")

var evenNumbers = [4, 6, 8]
print("Array2: \(evenNumbers)")

// Concatenate two arrays
primeNumbers.append(contentsOf: evenNumbers)
print("Array after append: \(primeNumbers)") // Array after append: [2, 3, 5, 4, 6, 8]

// Adding elements of various types
primeNumbers.append("Seven")
primeNumbers.append(7.0)

print("Array with multiple types: \(primeNumbers)") // Array with multiple types: [2, 3, 5, 4, 6, 8, "Seven", 7.0]
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal