斯威夫特:与indexOf的第二次出现 [英] Swift: second occurrence with indexOf

查看:217
本文介绍了斯威夫特:与indexOf的第二次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let numbers = [1,3,4,5,5,9,0,1]

要找到第一个5,请使用:

To find the first 5, use:

numbers.indexOf(5)

我如何找到第二次出现?

How do I find the second occurence?

推荐答案

  • 列表项
  • 您可以按照以下步骤在剩余的数组切片中再次搜索元素的索引:

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

    编辑/更新: Xcode 11•Swift 5.1或更高版本

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

    测试:

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

    这篇关于斯威夫特:与indexOf的第二次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆