Real-Life Examples

Swift Arrays: Real-Life Examples

Arrays are everywhere: rendering lists, aggregating values, finding items, and transforming data.


Aggregate and Transform

Use filtermap, and reduce to process arrays declaratively.

Example

let scores = [72, 88, 95, 64, 83]
let passed = scores.filter { $0 >= 75 }
let curved = passed.map { $0 + 5 }
let average = curved.reduce(0, +) / curved.count
print(passed)
print(curved)
print("Average: \(average)")

Filter to keep passing scores, map to apply a curve, then reduce to compute an average.

Tip: Prefer declarative iteration for clarity and fewer bugs.



Search & Index

Check for membership and find the index of a value.

Example

let names = ["Kai", "Bjorn", "Stale"]
print(names.contains("Bjorn"))            // true
if let i = names.firstIndex(of: "Stale") {
  print(i)                                 // 2
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *