Skip to content
AgileLogics
5 min read

Common Array Operations

Prerequisites: Arrays

Arrays have many built-in methods for searching, sorting, and slicing.

Example

let nums = [5, 3, 8, 1, 3]

print(nums.sorted())
print(nums.sorted(by: >))
print(nums.contains(8))
print(nums.min() ?? 0)
print(nums.max() ?? 0)
print(nums.reduce(0, +))
print(nums.firstIndex(of: 8) ?? -1)
print(Array(nums.prefix(2)))
print(Array(nums.reversed()))
print(nums.map(String.init).joined(separator: "-"))

Expected output

[1, 3, 3, 5, 8]
[8, 5, 3, 3, 1]
true
1
8
20
2
[5, 3]
[3, 1, 8, 3, 5]
5-3-8-1-3
  • sorted() returns a new sorted array. sort() (without the "-ed") sorts a var array in place.
  • sorted(by: >) sorts in descending order — > is passed as the comparison.
  • min(), max(), and firstIndex(of:) return optionals, since the array could be empty or not contain the value.
  • reduce(0, +) adds everything up, starting from 0. The next lessons explain how reduce and map work.

Checking elements

let ages = [12, 25, 37, 8]

print(ages.contains { $0 >= 18 })
print(ages.allSatisfy { $0 > 0 })
print(ages.first(where: { $0 > 20 }) ?? 0)
true
true
25

The { $0 >= 18 } parts are closures — small pieces of code passed to a method. $0 means "the current element". The Closures lesson covers them properly.

Practice

Given let scores = [72, 95, 88, 95, 60], print the highest score, the average as a Double, and the scores sorted from highest to lowest.

Hint: the average is the sum divided by the count — convert both to Double first.

Show solution
let scores = [72, 95, 88, 95, 60]
print(scores.max() ?? 0)
print(Double(scores.reduce(0, +)) / Double(scores.count))
print(scores.sorted(by: >))
95
82.0
[95, 95, 88, 72, 60]