Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Arrays in Swift
Written by Team Kodeco

An array is a collection of elements that are ordered and can be accessed by an index. In Swift, arrays are zero-indexed, meaning the first element has an index of 0 and the last element has an index of count-1.

Here’s an example of how to create and use an array:

// create an array of integers
var numbers = [1, 2, 3, 4, 5]

// add an element to the array
numbers.append(6)
print(numbers) // [1, 2, 3, 4, 5, 6]

// access an element in the array
let firstNumber = numbers[0]
print(firstNumber) // 1

// modify an element in the array
numbers[1] = 20
print(numbers) // [1, 20, 3, 4, 5, 6]

You can also create an array with a specific size and type using the Array(repeating:count:) initializer:

let emptyStrings = Array(repeating: "", count: 5)
print(emptyStrings) // ["", "", "", "", ""]

It is important to note that arrays in Swift are value types, which means they are copied when they are passed as a function argument or assigned to a variable.

© 2024 Kodeco Inc.