Arrays help you store many items in order. You can add, insert, or remove items to change the list as you want.
Array operations (append, insert, remove) in 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.
var fruits = ["Apple", "Banana"] fruits.append("Cherry") // fruits is ["Apple", "Banana", "Cherry"]
var fruits = ["Apple", "Banana"] fruits.insert("Orange", at: 1) // fruits is ["Apple", "Orange", "Banana"]
var fruits = ["Apple", "Banana", "Cherry"] fruits.remove(at: 0) // fruits is ["Banana", "Cherry"]
var emptyArray: [String] = [] emptyArray.append("First") // emptyArray is ["First"]
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.
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)")
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.
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.