Arrays
var name = [value1, value2, value3]
name[0]
name.append(value)
name.remove(at: index)
name.count
name.isEmpty
name.contains(value)
Creating and Accessing Arrays
An array is created with square brackets containing comma-separated values, and its elements are accessed by zero-based integer index.
Example: Creating and Accessing Arrays
// Declare a mutable variable `fruits`, initialized to `["apple", "banana", "cherry"]`
var fruits = ["apple", "banana", "cherry"]
// Print `fruits[0]` to the console
print(fruits[0])
// Print `fruits[2]` to the console
print(fruits[2])
// Print "Total fruits: \(fruits.count)" to the console
print("Total fruits: \(fruits.count)")
Login to try C/C++/Java/PHP code in the editor
Modifying an Array
Elements can be added with .append(), removed with .remove(at:), and updated by assigning directly to an index.
Example: Modifying an Array
// Declare a mutable variable `numbers`, initialized to `[1, 2, 3]`
var numbers = [1, 2, 3]
// Append `4` to `numbers`
numbers.append(4)
numbers.remove(at: 0)
numbers[0] = 99
// Print `numbers` to the console
print(numbers)
Login to try C/C++/Java/PHP code in the editor
Checking Array Contents
Properties like .isEmpty and .count, along with methods like .contains(), help inspect an array without manual loops.
Example: Checking Array Contents
// Declare a constant `scores`, set to `[80, 95, 70]`
let scores = [80, 95, 70]
// Print "Is empty: \(scores.isEmpty)" to the console
print("Is empty: \(scores.isEmpty)")
// Print "Count: \(scores.count)" to the console
print("Count: \(scores.count)")
// Print "Contains 95: \(scores.contains(95))" to the console
print("Contains 95: \(scores.contains(95))")
Login to try C/C++/Java/PHP code in the editor
- Trying to access an index that's out of bounds, e.g.
array[10]on a 3-element array, which crashes at runtime instead of returning nil. - Forgetting that arrays declared with
letare immutable -- you cannot append or remove elements from a constant array. - Confusing
.count(number of elements) with the last valid index, which is.count - 1.
- An array is an ordered, indexable collection of values of the same type, written as
[Type]. - Arrays declared with
varcan be modified; those declared withletcannot. - Common operations include
.append(),.remove(at:),.count, and indexing with[]. - Accessing an out-of-bounds index crashes the program at runtime.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: