理解 compactMap 和 flatMap 的问题

Issue in understanding compactMap & flatMap

我已经从多个教程中学习了 flatMap/compactMap 用于 flatten 数组的数组,但在我的情况下它不起作用或者我没有正确理解它。

let myArray = [["Raja","Kumar", nil,"Waqas"],["UAE","SINGAPORE","dUBAI","HONGKONG"]]
let final = myArray.compactMap{ [=10=] }

print("Result:\(final)")

输出:

Result:[[Optional("Raja"), Optional("Kumar"), nil, Optional("Waqas")], [Optional("UAE"), Optional("SINGAPORE"), Optional("dUBAI"), Optional("HONGKONG")]]

我尝试从上面的数组中删除 nil 但它仍然没有展平我的数组。

如有任何帮助,我们将不胜感激。

.compactMap

...用于生成没有可选对象的列表,您需要在获得 nils 的内部数组上使用 compactMap,如下所示:

let result = myArray.map { [=10=].compactMap { [=10=] } }

结果: [["Raja", "Kumar", "Waqas"], ["UAE", "SINGAPORE", "dUBAI", "HONGKONG"]]


.flatmap

...用于压扁集合集合,例如

let result = myArray.flatMap { [=11=].compactMap { [=11=] } }

结果: ["Raja", "Kumar", "Waqas", "UAE", "SINGAPORE", "dUBAI", "HONGKONG"]

compactMap应该用来从Optional个数组中过滤掉nil个元素,而flatMap可以用来压平一个多维数组.但是,您需要两者都做。

let final = myArray.flatMap{[=10=].compactMap{[=10=]}}

print("Result:\(final)")

请阅读文档

map(_:)

Returns an array containing the results of mapping the given closure over the sequence’s elements.

compactMap(_:)

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

flatMap(_:)

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

每个讨论部分包含一个示例。