let numbers = [1,3,4,5,9,1]
要找到前5个,请使用:
numbers.indexOf(5)
我如何找到第二次出现?
您可以在剩余的数组切片上执行另一个元素索引搜索,如下所示:
原文链接:https://www.f2er.com/swift/320011.html编辑/更新:Xcode 9•Swift 4
extension Collection where Element: Equatable { func secondIndex(of element: Element) -> Index? { guard let index = index(of: element) else { return nil } return self[self.index(after: index)...].index(of: element) } func indexes(of element: Element) -> [Index] { var indexes: [Index] = [] var position = self.startIndex while let index = self[position...].index(of: element) { indexes.append(index) position = self.index(after: index) } return indexes } }
测试:
let numbers = [1,1] numbers.secondIndex(of: 5) // 4 numbers.indexes(of: 5) // [3,4]