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

要查找第一个5,请使用:
numbers.indexOf(5)

我如何找到第二次出现?

最佳答案

  • 列表项

  • 您可以按照以下步骤在剩余的数组切片中再次搜索element的索引:
    编辑/更新: 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\n"
    } else {
        print("not found")
    }
    if let index = numbers.secondIndex(where: { $0.isMultiple(of: 3) }) {
        print(index)    // "5\n"
    } else {
        print("not found")
    }
    

    关于 swift :与indexOf的第二次出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34972688/

    10-13 05:29