当前位置: 首页 > 面试题库 >

Swift: second occurrence with indexOf

祁俊喆
2023-03-14
问题内容
let numbers = [1,3,4,5,5,9,0,1]

To find the first 5, use:

numbers.indexOf(5)

How do I find the second occurence?


问题答案:
  • List item

You can perform another search for the index of element at the remaining array
slice as follow:

edit/update: Xcode 11 • Swift 5.1 or later

extension Collection where Element: Equatable {
    func secondIndex(of element: Element) -> Index? {
        self[(firstIndex(of: element) ?? endIndex)...].dropFirst().firstIndex(of: element)
    }
}

Testing:

let numbers = [1,3,4,5,5,9,0,1]
numbers.secondIndex(of: 5)         // 4


 类似资料:

相关阅读

相关文章

相关问答