Swift: second occurrence with indexOf

后端 未结 6 1277
我寻月下人不归
我寻月下人不归 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:24

    Here's a general use extension of Array that will work for finding the nth element of a kind in any array:

    extension Array where Element: Equatable {
        // returns nil if there is no nth occurence
        // or the index of the nth occurence if there is
        func findNthIndexOf(n: Int, thing: Element) -> Int? {
            guard n > 0 else { return nil }
            var count = 0
            for (index, item) in enumerate() where item == thing {
                count += 1
                if count == n {
                    return index
                }
            }
            return nil
        }
    }
    
    let numbers = [1,3,4,5,5,9,0]
    
    numbers.findNthIndexOf(2, thing: 5) // returns 4
    

提交回复
热议问题