Swift:第二次出现 indexOf [英] Swift: second occurrence with indexOf

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

问题描述

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

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

To find the first 5, use:

numbers.indexOf(5)

如何找到第二次出现?

推荐答案

  • 列表项
  • 您可以在剩余的数组切片上再次搜索元素的索引,如下所示:

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

    编辑/更新:Swift 5.2 或更高版本

    extension Collection where Element: Equatable {
        /// Returns the second index where the specified value appears in the collection.
        func secondIndex(of element: Element) -> Index? {
            guard let index = firstIndex(of: element) else { return nil }
            return self[self.index(after: index)...].firstIndex(of: element)
        }
    }
    


    extension Collection {
        /// Returns the second index in which an element of the collection satisfies the given predicate.
        func secondIndex(where predicate: (Element) throws -> Bool) rethrows -> Index? {
            guard let index = try firstIndex(where: predicate) else { return nil }
            return try self[self.index(after: index)...].firstIndex(where: predicate)
        }
    }
    

    测试:

    let numbers = [1,3,4,5,5,9,0,1]
    if let index = numbers.secondIndex(of: 5) {
        print(index)    // "4
    "
    } else {
        print("not found")
    }    
    if let index = numbers.secondIndex(where: { $0.isMultiple(of: 3) }) {
        print(index)    // "5
    "
    } else {
        print("not found")
    }
    

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

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