Programming in Swift: Functions & Types

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

Part 2: Closures

15. compactMap & flatMap

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

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: 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.

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