理解compactMap和flatMap的问题

Muh*_*ati 2 arrays flatmap swift

我已经从flatMap/compactMap用于flatten数组数组的多个教程中进行了遍历,但就我而言,它不起作用或无法正确理解。

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

print("Result:\(final)")
Run Code Online (Sandbox Code Playgroud)

输出:

Result:[[Optional("Raja"), Optional("Kumar"), nil, Optional("Waqas")], [Optional("UAE"), Optional("SINGAPORE"), Optional("dUBAI"), Optional("HONGKONG")]]
Run Code Online (Sandbox Code Playgroud)

我尝试从上述数组中删除nil,但仍然不能使我的数组变平。

任何帮助将非常感激。

Aam*_*irR 5

.compactMap

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

let result = myArray.map { $0.compactMap { $0 } }
Run Code Online (Sandbox Code Playgroud)

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


.flatmap

...用于拼合馆藏,例如

let result = myArray.flatMap { $0.compactMap { $0 } }
Run Code Online (Sandbox Code Playgroud)

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


Dáv*_*tor 5

compactMap应该用于nilOptionals数组中过滤出元素,而flatMap可以用于展平多维数组。但是,您需要同时执行这两项操作。

let final = myArray.flatMap{$0.compactMap{$0}}

print("Result:\(final)")
Run Code Online (Sandbox Code Playgroud)