Programming in Swift: Functions & Types

Jan 4 2022 Swift 5.5, iOS 15, Xcode 13

Part 2: Closures

15. compactMap & flatMap

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: 14. forEach & map Next episode: 16. Challenge: Closures & Collections

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.

There are two more handy methods with map in the name: compactMap and flatMap. Both of them return an array, like map, but they also do a little more work for you behind the scenes.

var arrayForValidInput: [Int] = []
for input in userInput {

}
  guard let input = Int(input) else {
    continue
  }
  arrayForValidInput.append(input)
} 
arrayForValidInput 
let validInput = userInput.compactMap { input in
  
}
let validInput = userInput.compactMap { 
  
}
let validInput = userInput.compactMap { 😺input in🛑
  
}
Int(input)
let dwarvesAfterM = 
let dwarvesAfterM = arrayOfDwarfArrays.flatMap { 
  
}
let dwarvesAfterM = arrayOfDwarfArrays.flatMap { 😺dwarves 
  
}
let dwarvesAfterM = arrayOfDwarfArrays.flatMap { dwarves 😺-> [String] in
  
}
dwarves
  var afterM: [String] = []
for dwarf in dwarves where dwarf > "M" {

}
    afterM.append(dwarf)
return afterM
var afterM: [String] = []
  for dwarf in dwarves where dwarf > "M" {
    afterM.append(dwarf)
  }
  return afterM