Last active
May 3, 2018 23:03
-
-
Save kristopherjohnson/9f176a1be3c8a7f6065c to your computer and use it in GitHub Desktop.
Swift: Find index of first element of sequence matching a predicate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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)" |
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
Really nice one!
Would it be better to extend the SequenceType?
If not, also better switching the arguments so to have predisposition for currying.