Today I’m starting
On Monday I was told by someone who has not steered me wrong yet, “I would highly recommend to stop anything that you are reading or listening to the moment and start Shoe Dog.”
On Tuesday I began listening to this book, which is a memoir by Phil Knight, the creator of Nike. One of the the first lines of the book resonated with me: “Why is it always so hard to get started?”.
I used to keep a blog of my adventures when I was living abroad, and I have been meaning to begin writing regularly again, though with a focus on my day to day experiences and learnings as an engineer in the Silicon Valley.
It has been difficult to start that habit, but today is the day.
Mark my words, I intend to share one thing I learn each day.
Feb 22, 2017
TIL: .flatMap()
TL;DR: .flatMap is a way to flatten nested arrays, so [[1, 2, 3], [4, 5, 6]] is treated as [1, 2, 3, 4, 5, 6]
Some more detailed learnings:
.flatMap doesn’t operate on the contents of the array, it operates on the array itself
The flatMap() function doesn’t see the world as entirely flat, it just sees one less dimension than map() and the rest of the Swift world. Therefore, [[[1],[2,3]],[[4,5],[6]]] would flatMap() to [[1], [2, 3], [4, 5], [6]], for example.
(Thanks sketchytech)
Another great use case is how it handles optionals (thanks Natasha the Robot):
.flatMap strips out the nil values in optional-type arrays to return arrays of unwrapped values: [Int?] = [1, 2, nil, 5, nil, 7] → [1, 2, 5, 7]
As for a concrete example of how I implemented it:
We handle survey responses as an array of dictionaries in which the key is a response and value is an array of answers. I needed to parse through the answers.
The solution implementing .flatMap() is like so:
```
let responsesDictionary = jsonDictionary[“responses”] as? [[String: Any]]
let responses: [VASurveyCustomerResponse] = responsesDictionary.flatMap() {
VASurveyCustomerResponse(jsonDictionary: $0)
}
```
And that’s how you .flatMap() a multidimensional array in Swift 3.
