我需要执行以下操作
let array = [1, 2, nil, 3, nil, 4, 5]
var positions: [Int] = []
for (index, val) in array.enumerated() where val == nil {
positions.append(index)
}
print(positions) //gives [2, 4]
,而不必执行for
循环。有可能吗?
答案 0 :(得分:5)
过滤indices
let array = [1, 2, nil, 3, nil, 4, 5]
let positions = array.indices.filter{array[$0] == nil}
答案 1 :(得分:3)
您可以compactMap
枚举:
let array = [1, 2, nil, 3, nil, 4, 5]
let positions = array.enumerated().compactMap { (offset, value) in
value == nil ? offset : nil
}
print(positions) // [2, 4]