0
0
Swiftprogramming~5 mins

Array operations (append, insert, remove) in Swift

Choose your learning style9 modes available
Introduction

Arrays help you store many items in order. You can add, insert, or remove items to change the list as you want.

You want to keep a list of your favorite songs and add new ones.
You need to insert a new task in the middle of your to-do list.
You want to remove a finished item from your shopping list.
You are collecting scores in a game and want to update the list.
You want to keep track of names and change the list as people join or leave.
Syntax
Swift
var arrayName: [Type] = []

// Append adds an item at the end
arrayName.append(newItem)

// Insert adds an item at a specific position
arrayName.insert(newItem, at: index)

// Remove deletes an item at a specific position
arrayName.remove(at: index)

Arrays in Swift start with index 0 for the first item.

Make sure the index is within the array size when inserting or removing.

Examples
Append adds "Cherry" to the end of the fruits array.
Swift
var fruits = ["Apple", "Banana"]
fruits.append("Cherry")
// fruits is ["Apple", "Banana", "Cherry"]
Insert adds "Orange" at position 1, pushing "Banana" to the right.
Swift
var fruits = ["Apple", "Banana"]
fruits.insert("Orange", at: 1)
// fruits is ["Apple", "Orange", "Banana"]
Remove deletes the first item "Apple" from the array.
Swift
var fruits = ["Apple", "Banana", "Cherry"]
fruits.remove(at: 0)
// fruits is ["Banana", "Cherry"]
Appending to an empty array adds the first item.
Swift
var emptyArray: [String] = []
emptyArray.append("First")
// emptyArray is ["First"]
Sample Program

This program shows how to add, insert, and remove items in a Swift array. It prints the array before and after each operation so you can see the changes.

Swift
import Foundation

// Define an array of strings
var colors = ["Red", "Green", "Blue"]

// Print original array
print("Original colors: \(colors)")

// Append a new color
colors.append("Yellow")
print("After append: \(colors)")

// Insert a color at index 2
colors.insert("Orange", at: 2)
print("After insert at index 2: \(colors)")

// Remove the color at index 1
colors.remove(at: 1)
print("After remove at index 1: \(colors)")
OutputSuccess
Important Notes

Appending an item is fast and usually takes constant time O(1).

Inserting or removing items in the middle can take longer because Swift shifts other items. This is O(n) time where n is the number of items.

Be careful with indexes: inserting or removing at an invalid index causes a runtime error.

Use append when adding to the end, insert when you need a specific position, and remove to delete unwanted items.

Summary

Arrays store ordered lists of items you can change.

Use append to add at the end, insert to add anywhere, and remove to delete items.

Always check indexes to avoid errors.