Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何在没有循环的情况下获得过滤数组中元素的位置_Arrays_Swift_Xcode - Fatal编程技术网

Arrays 如何在没有循环的情况下获得过滤数组中元素的位置

Arrays 如何在没有循环的情况下获得过滤数组中元素的位置,arrays,swift,xcode,Arrays,Swift,Xcode,我需要执行以下操作 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] 无需为循环执行。可能吗?过滤索引 let array = [1, 2, nil, 3, nil, 4, 5]

我需要执行以下操作

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]

无需为循环执行
。可能吗?

过滤
索引

let array = [1, 2, nil, 3, nil, 4, 5]
let positions = array.indices.filter{array[$0] == nil}
您可以在枚举中执行以下操作:

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]

也许可以使用
filter
吗?在这种情况下,
map
将同样有效,因为
enumerated()
永远不会包含nil值?@JoakimDanielson:不,什么不起作用
enumerated()
枚举偏移量和值而不进行任何筛选,并且值的类型为
Int?
。使用
map()
时,结果将是
[nil,nil,Optional(2),nil,Optional(4),nil,nil]
map
在这里不起作用,因为所需的结果不仅仅是转换为另一种类型,还包括过滤
enumerated()
不像
compactMap
那样工作,它将作为
map
工作,提供
EnumeratedSequence
的列表,其中
数组
元素可以是
可选的
。是的,我的错了。我在想
filter
+
map
@JoakimDanielson:是的,可以把compactMap看作是“filter+map”