Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Look for a subarray in an array in Swift
extension Collection {
/// True if `self` is a range within `collection`
/// - Parameter collection: a `Collection` like `Array`
/// - Returns: true or false
///
/// Since this works with `Collection` it works with `Array`, `ArraySlic`, etc..
func isSubcollection<U>(of collection:U) -> Bool
where U:Collection, U.Element == Self.Element, Self.Element:Equatable
{
let (a,b) = (collection,self)
for i in a.indices {
var matches:Bool = true
var i_runahead = i
for j in b.indices {
if b[j] != a[i_runahead] {
matches = false
break;
}
i_runahead = a.index(after: i_runahead)
}
if matches { return true }
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment