Swift: second occurrence with indexOf

后端 未结 6 1268
我寻月下人不归
我寻月下人不归 2020-12-10 07:09
let numbers = [1,3,4,5,5,9,0,1]

To find the first 5, use:

numbers.indexOf(5)

How do I find the secon

6条回答
  •  醉梦人生
    2020-12-10 07:33

    extension Collection where Element: Equatable {
        func nth(occurance: Int, of element: Element) -> Index? {
            var level : Int = occurance
            var position = self.startIndex
            while let index = self[position...].index(of: element) {
                level -= 1
                guard level >= 0 else { return nil }
                guard level != 0 else { return index }
                position = self.index(after: index)
            }
            return nil
        }
    }
    

提交回复
热议问题