Swift Collections

Swift has three main collection types: Array, Dictionary, and Set.

Arrays

SWIFT
var fruits = ["apple", "banana", "mango"]
fruits.append("orange")
fruits.insert("kiwi", at: 1)
fruits.remove(at: 0)

for fruit in fruits { print(fruit) }

let upper = fruits.map { $0.uppercased() }
let long = fruits.filter { $0.count > 4 }

Dictionaries

SWIFT
var scores: [String: Int] = ["Ram": 85, "Sita": 92]
scores["Gita"] = 95
scores.removeValue(forKey: "Ram")

for (name, score) in scores {
    print("\(name): \(score)")
}

Sets (Unique Values)

SWIFT
var colors: Set<String> = ["red", "blue", "green"]
colors.insert("red")  // ignored

let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5, 6]
print(a.union(b))          // {1, 2, 3, 4, 5, 6}
print(a.intersection(b))   // {3, 4}

Tips

  • Use Array for ordered, Set for unique, Dictionary for key-value.
  • Use map, filter, reduce for functional transformations.

🎉 You have completed the Swift course!