Skip to content

Instantly share code, notes, and snippets.

Last active March 13, 2021 18:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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
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