Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

swift3.0.2 - Swift: second occurrence with indexOf

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

To find the first 5, use:

numbers.indexOf(5)

How do I find the second occurence?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • List item

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

edit/update: Swift 5.2 or later

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)
    }
}

Testing:

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")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...