Arrays
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
var fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[2])
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
var numbers = [1, 2, 3]
numbers.append(4)
numbers.remove(at: 0)
numbers[0] = 99
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
let scores = [80, 95, 70]
print("Is empty: \(scores.isEmpty)")
print("Count: \(scores.count)")
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: