Programming in Swift: Functions & Types

Jan 4 2022 · Swift 5.5, iOS 15, Xcode 13

Part 2: Closures

14. forEach & map

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

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

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 14. forEach & map

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.

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)