在索引处查找对象值,并使用swift将其存储在其他数组中。
有人可以告诉我以下代码段的最优化方法吗?
var selectedIndex = [1,3,5]
var allData : [Person] = []
var ids: [Int] = []
for (index, item) in allData.enumerated() {
for id in selectedIndex {
if id == index {
ids.append(item.id)
}
}
}
答案 0 :(得分:3)
如果您确定所有索引均有效,则可以映射所选索引:
let ids = selectedIndex.map {
allData[$0].id
}
如果要确保所选索引存在于allData中:
let ids = selectedIndex.compactMap {
allData.indices ~= $0 ? allData[$0].id : nil
}
答案 1 :(得分:0)
由于索引已排序,因此您可以使用allData
仅获取所需的prefix
部分。
let ids =
allData
.prefix(selectedIndices.last.map { $0 + 1 } ?? 0)
.enumerated()
.compactMap {
Optional($0)
.filter { selectedIndices.contains($0.offset) }?
.element.id
}
public extension Optional {
/// Transform `.some` into `.none`, if a condition fails.
/// - Parameters:
/// - isSome: The condition that will result in `nil`, when evaluated to `false`.
func filter(_ isSome: (Wrapped) throws -> Bool) rethrows -> Self {
try flatMap { try isSome($0) ? $0 : nil }
}
}