Let's start with a map
. It takes a function, and keeps applying it for every element, and then returns all of them as an array
let arr = [1, 2, 3]
func multiplyByTwo(_ integer: Int) -> Int {
return integer * 2
}
print(arr.map(multiplyByTwo)) // [2, 4, 6]
but usually you don't want to make a function just to pass it to map
, so usually we use a closure for that. $0
here means the (first) argument to the closure.
let arr = [1, 2, 3]
print(arr.map { $0 * 2 }) // [2, 4, 6]
So let's try to use map
to get all all key3 from the array of dictionaries (I added a third dictionary to better make my point)
var arrayDictionaries: [[String: Any]] = [["key1": 1.1, "key2": 2.1, "key3": "value3.1"], ["key1": "value1.2", "key2": "value2.2", "key3": "value3.3"], ["key1": "value1.3"]]
print(arrayDictionaries.map { $0["key3"] }) // [Optional("value3.1"), Optional("value3.3"), nil]
It does what we want, which is to extract all key3, but everything is optional and there is a nil. To get rid of that, we use compactMap
, which is just like map
, but skips the nils afterwards. Notice how there are only two values extracted from three dictionaries
var arrayDictionaries: [[String: Any]] = [["key1": 1.1, "key2": 2.1, "key3": "value3.1"], ["key1": "value1.2", "key2": "value2.2", "key3": "value3.3"], ["key1": "value1.3"]]
print(arrayDictionaries.compactMap { $0["key3"] }) // ["value3.1", "value3.3"]