[0, 2, 4] items.w-6ren">
gpt4 book ai didi

arrays - Swift - 如何获取数组过滤项的索引

转载 作者:IT王子 更新时间:2023-10-29 05:13:43 25 4
gpt4 key购买 nike

let items: [String] = ["A", "B", "A", "C", "A", "D"]

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]

Swift 3 是否支持像 whatFunction(_: Element) 这样的函数?

如果不是,最有效的逻辑是什么?

最佳答案

可以直接过滤数组的indices,避免额外的mapping。

let items = ["A", "B", "A", "C", "A", "D"]
let filteredIndices = items.indices.filter {items[$0] == "A"}

或作为数组扩展:

extension Array where Element: Equatable {

func whatFunction(_ value : Element) -> [Int] {
return self.indices.filter {self[$0] == value}
}

}

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]

或者更通用

extension Collection where Element: Equatable {

func whatFunction(_ value : Element) -> [Index] {
return self.indices.filter {self[$0] == value}
}

}

关于arrays - Swift - 如何获取数组过滤项的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45933149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com