一尘不染

Swift: second occurrence with indexOf

swift

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?


阅读 221

收藏
2020-07-07

共1个答案

一尘不染

  • 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
2020-07-07