Lesson 47Closures

Map Function

What is Map?

The map function transforms every element in a collection using a closure. It returns a new array with the transformed values!

Map vs For Loop

For Loop (verbose)

var result: [Int] = []
for n in numbers {
    result.append(n * 2)
}

Map (concise)

let result = numbers.map { $0 * 2 }

One line, functional style!

Map Variants

mapTransform each element
compactMapTransform + remove nils
flatMapTransform + flatten nested arrays
mapValuesTransform dictionary values only

Key Points

  • Map returns a new array - original unchanged
  • Output array has same count as input
  • Can change element types (Int → String)
  • Works on arrays, optionals, dictionaries

Common Use Cases

Data transformationType conversionExtract propertiesFormat strings
main.swift
// THE MAP FUNCTION
// Transform every element in a collection
// Returns a NEW array with transformed values

let numbers = [1, 2, 3, 4, 5]

// BASIC MAP
let doubled = numbers.map { $0 * 2 }
print(doubled)  // [2, 4, 6, 8, 10]

// Equivalent to:
var doubledManual: [Int] = []
for n in numbers {
    doubledManual.append(n * 2)
}

// MAP WITH STRINGS
let names = ["alice", "bob", "charlie"]
let uppercased = names.map { $0.uppercased() }
print(uppercased)  // ["ALICE", "BOB", "CHARLIE"]

let lengths = names.map { $0.count }
print(lengths)  // [5, 3, 7]

// MAP CAN CHANGE TYPES
let numbersAsStrings = numbers.map { String($0) }
print(numbersAsStrings)  // ["1", "2", "3", "4", "5"]

let prices = [10.5, 20.0, 15.75]
let formatted = prices.map { "$\(String(format: "%.2f", $0))" }
print(formatted)  // ["$10.50", "$20.00", "$15.75"]

// MAP WITH CUSTOM OBJECTS
struct User {
    let name: String
    let age: Int
}

let users = [
    User(name: "Alice", age: 25),
    User(name: "Bob", age: 30),
    User(name: "Charlie", age: 35)
]

let userNames = users.map { $0.name }
print(userNames)  // ["Alice", "Bob", "Charlie"]

let userDescriptions = users.map { "\($0.name) is \($0.age)" }
print(userDescriptions)

// MAP ON OPTIONALS
let optionalNumber: Int? = 5
let doubled2 = optionalNumber.map { $0 * 2 }
print(doubled2 as Any)  // Optional(10)

let nilNumber: Int? = nil
let doubled3 = nilNumber.map { $0 * 2 }
print(doubled3 as Any)  // nil (doesn't crash!)

// MAP ON DICTIONARIES
let scores = ["Alice": 85, "Bob": 92, "Charlie": 78]

// Returns array of tuples
let increased = scores.map { (name, score) in
    (name, score + 5)
}
print(increased)

// MAPVALUES - keeps dictionary structure
let bonusScores = scores.mapValues { $0 + 10 }
print(bonusScores)  // ["Alice": 95, "Bob": 102, "Charlie": 88]

// CHAINING MAP
let result = numbers
    .map { $0 * 2 }      // [2, 4, 6, 8, 10]
    .map { $0 + 1 }      // [3, 5, 7, 9, 11]
    .map { String($0) }  // ["3", "5", "7", "9", "11"]
print(result)

// COMPACTMAP - removes nil values
let strings = ["1", "2", "three", "4", "five"]
let validNumbers = strings.compactMap { Int($0) }
print(validNumbers)  // [1, 2, 4] - "three" and "five" removed

// FLATMAP - flattens nested arrays
let nested = [[1, 2], [3, 4], [5, 6]]
let flattened = nested.flatMap { $0 }
print(flattened)  // [1, 2, 3, 4, 5, 6]

Try It Yourself!

Use map to convert an array of temperatures in Celsius to Fahrenheit: [0, 20, 100][32, 68, 212]