Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active January 29, 2025 06:06
Show Gist options
  • Save kristopherjohnson/9f176a1be3c8a7f6065c to your computer and use it in GitHub Desktop.
Save kristopherjohnson/9f176a1be3c8a7f6065c to your computer and use it in GitHub Desktop.
Swift: Find index of first element of sequence matching a predicate
/// Find the index of the first element of a sequence that satisfies a predicate
///
/// :param: sequence A sequence to be searched
/// :param: predicate A function applied to each element in turn until it returns true
///
/// :returns: Zero-based index of first element that satisfies the predicate, or nil if no such element was found
public func findIndex<S: SequenceType>(sequence: S, predicate: (S.Generator.Element) -> Bool) -> Int? {
for (index, element) in enumerate(sequence) {
if predicate(element) {
return index
}
}
return nil
}
// Example
let array = ["One", "Two", "Three", "Four"]
// find index of first item that starts with "Th"
let firstTh = findIndex(array) { $0.hasPrefix("Th") }
println("firstTh = \(firstTh)") // "firstTh = Optional(2)"
@kristopherjohnson
Copy link
Author

Yes, it would be better to extend SequenceType. This was written before protocol extensions were available in Swift.

Note that CollectionType has an indexOf method which is similar. (I don't remember whether it was present when I wrote this.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment