Arrays in Swift: Creating, Adding, Removing, Slicing, Sorting and Safe Indexing

Swift 55 min min read Updated: Nov 21, 2026 Beginner
Arrays in Swift: Creating, Adding, Removing, Slicing, Sorting and Safe Indexing
Beginner Topic 1 of 3

Creating Arrays

swift var scores = [90, 72, 85] var names: [String] = [] let zeros = Array(repeating: 0, count: 3) print(scores, names, zeros) print(scores.count, scores.isEmpty)
Output

[90, 72, 85] [] [0, 0, 0] | 3 false

Adding, Changing and Removing

swift var list = ["a", "b", "c"] list.append("d") list.insert("z", at: 0) list[1] = "A" let removed = list.remove(at: 2) print(list, removed) list.removeAll(where: { $0 == "d" }) print(list)
Output

["z", "A", "c", "d"] b | ["z", "A", "c"]

Safe Indexing

Asking for an index that does not exist crashes the program. Check first, or use first and last, which return optionals.

swift let items = [10, 20, 30] print(items.first as Any, items.last as Any) let index = 5 if items.indices.contains(index) { print(items[index]) } else { print("no item at", index) } print([Int]().first as Any)
Output

Optional(10) Optional(30) | no item at 5 | nil

Sorting and Searching

swift let nums = [5, 2, 9, 1] print(nums.sorted(), nums.sorted(by: >)) print(nums.contains(9), nums.firstIndex(of: 9) as Any) print(nums.min() as Any, nums.max() as Any) let words = ["pear", "fig", "banana"] print(words.sorted { $0.count < $1.count })
Output

[1, 2, 5, 9] [9, 5, 2, 1] | true Optional(2) | Optional(1) Optional(9) | ["fig", "pear", "banana"]

Slices

swift let a = [1, 2, 3, 4, 5] let part = a[1...3] print(part, Array(part)) print(a.prefix(2), a.suffix(2))
Output

[2, 3, 4] [2, 3, 4] | [1, 2] [4, 5]

Slice indexes A slice keeps the original indexes. a[1...3] starts at index 1, not 0. Convert with Array(...) when you want a fresh array.

Arrays Are Values

swift var first = [1, 2, 3] var second = first // a separate copy (copy on write) second.append(4) print(first, second)
Output

[1, 2, 3] [1, 2, 3, 4]

Common Mistakes

  • Reading an index that is out of range
  • Forgetting that a slice keeps the original indexes
  • Using first! on an array that may be empty

Practice

  1. Create an array of five numbers and print the sum with a loop
  2. Remove all negative numbers
  3. Sort names by length, then alphabetically

Conclusion

Arrays keep order, behave like separate values when copied, and need careful indexing.

Quick Summary: Create; modify; safe index; sort; slice; value semantics.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators