How to pass parameter to custom iterator

I'm making a custom iterator that returns every slice of a given width through a collection. I got it working with a hardcoded width but can't figure out how to make it a parameter. I want the hard-coded 3 to be replaced with that param:
extension Array {
    
    func windows() -> AnySequence<ArraySlice<Element>> {
        return AnySequence({ () -> AnyIterator<ArraySlice<Element>> in
            var index = self.startIndex
            
            return AnyIterator({
                if index > self.count - 3 {
                    return nil
                }
                
                let result = self[index..<index + 3]
                
                self.formIndex(after: &index)

                return result
            })
        })
    }
    
}

let seq = [1,11,7,444]
for val in seq.windows() {
    print(val)
}
Was this page helpful?