![](/img/trans.png)
[英]ObjectiveC-NSMutable array specific indexes stored in another array
[英]How to get the items of an array based on the indexes stored in another array
我有兩個 arrays:
let a = ["apple","banana","orange","pomelo","kiwi","melon"]
let b = [1, 2, 4]
a
包含所有項目, b
包含我感興趣的項目的索引。
所以我想創建一個 function 來提取數組b
中指定的索引處的項目。
我可以用 for 循環做 tis:
for i in 0...a.count-1{
if i == b[i]{
print(a[i])
}
}
為了清楚起見,所需的 output 將是:
香蕉橙獼猴桃
問題是如果數字很大,for 循環會太慢。
我想知道是否存在復雜性較低的東西。
您可以簡單地 map 索引並返回相關元素:
let aa = ["apple","banana","orange","pomelo","kiwi","melon"]
let bb = [1, 2, 4]
let elements = bb.map { aa[$0] }
print(elements) // ["banana", "orange", "kiwi"]
或擴展 RandomAccessCollection 協議:
extension RandomAccessCollection {
func elements(at indices: [Index]) -> [Element] { indices.map { self[$0] } }
}
let a = ["apple","banana","orange","pomelo","kiwi","melon"]
let b = [1, 2, 4]
let elements = a.elements(at: b) // ["banana", "orange", "kiwi"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.