Skip to content

Instantly share code, notes, and snippets.

@algal
Last active March 13, 2021 18:37
Show Gist options
  • Save algal/9403f238179a71824d39319b19257817 to your computer and use it in GitHub Desktop.
Save algal/9403f238179a71824d39319b19257817 to your computer and use it in GitHub Desktop.
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