Ray Wenderlich Functions and Types Course - Part 4
Wanted to code at the weekend but had literally no time to! So a quick 20 minutes now, if that!
Start Time - 17:38
Two more handy methods - compact map and flat map!
Compact Map and Flat Map
Compact - helps us deal with optionals. Iterates through each element then add resulting values if they are non nil.
Flat - multi dimensional array - combine arrays into 1!
This is how you would use a for loop to go through an array and convert what you can to an int -
Start Time - 17:38
Two more handy methods - compact map and flat map!
Compact Map and Flat Map
Compact - helps us deal with optionals. Iterates through each element then add resulting values if they are non nil.
Flat - multi dimensional array - combine arrays into 1!
This is how you would use a for loop to go through an array and convert what you can to an int -
var arrayForValidInput: [Int] = []
for input in userInput {
guard let input = Int(input) else {
continue
}
arrayForValidInput.append(input)
}
But of course compact map is much better!
let validInput = userInput.compactMap { (input) in
Int(input)
}
Flat Map
let arrayOfDwarfArrays = [
["Sleepy", "Grumpy", "Doc", "Bashful", "Sneezy"],
["Thorin", "Nori", "Bombur"]
]
// --------------------------------------
let afterMDwarfs = arrayOfDwarfArrays.flatMap { (dwarves) -> [String] in
var afterM: [String] = []
for dwarf in dwarves where dwarf > "M" {
afterM.append(dwarf)
}
return afterM
}
Apparently there is an easier way to do the above. But a challenge first.....
Challenge!
These are tough ones!
Done! Had to use ideas from previous couple of lessons but that's fine! Good stuff and nice to see within challenge
Paused at 18:12 (34 minutes so far)
That's it! No time for any more but some good progress with map. Next time will complete this section on closures.
Comments
Post a Comment