Swift - FlatMap unwrapping & flattening optional arrays

Mapping is perhaps the most underrated function in Swift 2.0. Allowing your code to be functional, concise and fast. However, I never realized there was a flatMap function until I read Natasha's blog post: (Great blog to follow btw)

http://natashatherobot.com/swift-2-flatmap/

FlatMap has the functionality of removing all the nil values in your array and returning an array of unwrapped values.

This can be insanely useful when dealing with arrays with optional elements as you would have to manually sort through them and remove the nil values.

let greatestPlayers : [String?] = [nil, “Kobe Bryant”, nil, “Michael Jordan”, nil, nil, nil, “Larry Bird”, “Magic Johnson”]

^Array with optional elements

To remove all the nil values you could...

var goat = [String]()
for player in greatestPlayers {
    guard let player = player else { continue }
    goat.append(player)
}
print(goat)
//["Kobe Bryant", "Michael Jordan", "Larry Bird", "Magic Johnson"]

Not Sexy.

With FlatMap...

let goat = greatestPlayers.flatMap{ $0 }
print(goat)
//["Kobe Bryant", "Michael Jordan", "Larry Bird", "Magic Johnson"]

Sexy.

The reason why it does that is because

extension SequenceType {
    public func flatMap<T>(@noescape transform:     (Self.Generator.Element) throws -> T?) rethrows -> [T]
}

Other uses of flatMap is you can use it to flatten arrays that are nested and sanitize it.

let corruptDataOfFruits: [String?] = [“Apple”, nil, “Banana”, nil, “Kiwi”, “Watermelon”, nil, nil]
let corrupDataOfDrinks: [String?] = [nil, nil, nil, “Beer”, “Milk”, “Water”, nil]
let groceryList = [corruptDataOfFruits, corrupDataOfDrinks].flatMap{ $0.flatMap{$0}}
print(groceryList)
//["Apple", "Banana", "Kiwi", "Watermelon", "Beer", "Milk", "Water"]

This not only removes all nil values, also flattens the array to a combined one dimension array.

Feel free to contact me!

GitHub | Twitter | Facebook | JackyWangDeveloper@gmail.com

Thanks for reading, Happy Coding!