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,但仍然不能使我的数组变平。
任何帮助将非常感激。
.compactMap...用于产生没有可选对象的列表,您需要compactMap在nils 所在的内部数组上使用,如下所示:
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"]
compactMap应该用于nil从Optionals数组中过滤出元素,而flatMap可以用于展平多维数组。但是,您需要同时执行这两项操作。
let final = myArray.flatMap{$0.compactMap{$0}}
print("Result:\(final)")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |