gpt4 book ai didi

Swift:第二次出现 indexOf

转载 作者:搜寻专家 更新时间:2023-10-30 22:08:45 25 4
gpt4 key购买 nike

let numbers = [1,3,4,5,5,9,0,1]

要查找前 5,请使用:

numbers.indexOf(5)

如何找到第二次出现的地方?

最佳答案

  • 列表项

您可以对剩余数组切片中的元素索引执行另一次搜索,如下所示:

编辑/更新:Swift 5.2 或更高版本

extension Collection where Element: Equatable {
/// Returns the second index where the specified value appears in the collection.
func secondIndex(of element: Element) -> Index? {
guard let index = firstIndex(of: element) else { return nil }
return self[self.index(after: index)...].firstIndex(of: element)
}
}

extension Collection {
/// Returns the second index in which an element of the collection satisfies the given predicate.
func secondIndex(where predicate: (Element) throws -> Bool) rethrows -> Index? {
guard let index = try firstIndex(where: predicate) else { return nil }
return try self[self.index(after: index)...].firstIndex(where: predicate)
}
}

测试:

let numbers = [1,3,4,5,5,9,0,1]
if let index = numbers.secondIndex(of: 5) {
print(index) // "4\n"
} else {
print("not found")
}
if let index = numbers.secondIndex(where: { $0.isMultiple(of: 3) }) {
print(index) // "5\n"
} else {
print("not found")
}

关于Swift:第二次出现 indexOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972688/

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