Swift: second occurrence with indexOf

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

    I don't think you can do it with indexOf. Instead you'll have to use a for-loop. A shorthand version:

    let numbers = [1,3,4,5,5,9,0,1]
    var indexes = [Int]()
    numbers.enumerate().forEach { if $0.element == 5 { indexes += [$0.index] } }
    
    print(indexes) // [3, 4]
    

提交回复
热议问题