You can do this with higher level functions, for example:
func indexOf(data:[String], _ part:[String]) -> Int? { // This is to prevent construction of a range from zero to negative if part.count > data.count { return nil } // The index of the match could not exceed data.count-part.count return (0...data.count-part.count).indexOf {ind in // Construct a sub-array from current index, // and compare its content to what we are looking for. [String](data[ind..<ind+part.count]) == part } }
This function returns the index of the first match, if any, or nil otherwise.
You can use it as follows:
let mainArray = ["hello", "world", "it's", "a", "beautiful", "day"] if let index = indexOf(mainArray, ["world", "it's"]) { print("Found match at \(index)") } else { print("No match") }
Editing as an extension for a shared array ...
Now it can be used for any uniform array of Equatable types.
extension Array where Element : Equatable { func indexOfContiguous(subArray:[Element]) -> Int? { // This is to prevent construction of a range from zero to negative if subArray.count > self.count { return nil } // The index of the match could not exceed data.count-part.count return (0...self.count-subArray.count).indexOf { ind in // Construct a sub-array from current index, // and compare its content to what we are looking for. [Element](self[ind..<ind+subArray.count]) == subArray } } }
source share