Programming in Swift: Functions & Types

Jan 4 2022 Swift 5.5, iOS 15, Xcode 13

Part 2: Closures

14. forEach & map

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 13. Challenge: Closure Syntax Next episode: 15. compactMap & flatMap

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Now that you know a bit about closures, you’re ready to see how they can be particularly useful when dealing with collections. Collections in Swift have several handy methods that take a closure as an argument. These closures are executed for each element in the collection, much like the body of a for loop!

init(priority: Task.Priority, names: [String]) {
  self.init(
    priority: priority,
    tasks: names.map 💛{ Task(name: $0) }💛
  )
}
for price in prices {
  print(price)
}
prices
prices.forEach(
prices.forEach { (<#Double#>) in
  <#code#>
}
prices.forEach { (😺price🛑) in
  😺print(price)🛑
}
prices.forEach { ❌(price) in❌
prices.forEach { print(😺$0🛑) }
var arrayForSalePrices: [Double] = []
for price in prices {

}
  arrayForSalePrices.append(price * 0.9)
arrayForSalePrices
let salePrices = 
let salePrices = 😺prices.map { (<#Double#>) -> T in
  <#code#>
}
let salePrices = prices.map { (😺price❌) -> T in
let salePrices = prices.map { (price) -> 😺Double❌ in
let salePrices = prices.map { price -> Double in
  price * 0.9
}
let salePrices = prices.map { 😺$0 * 0.9🛑 }
let priceLabels
let priceLabels = salePrices.map {...
 (price) -> String in
String(format: "%.2f", price)