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)
}
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)
}
1 Reply
hippietrail
hippietrailOP3y ago
figured it out. i thought i had to pass the parameter to AnySequence or AnyIterator but i only have to pass it to windows():
extension Array {

func windows(width: Int) -> AnySequence<ArraySlice<Element>> {
return AnySequence({ () -> AnyIterator<ArraySlice<Element>> in
var index = self.startIndex

return AnyIterator({
if index > self.count - width {
return nil
}

let result = self[index..<index + width]

self.formIndex(after: &index)

return result
})
})
}

}

let seq = [1,11,333,33,5,623,123,44,7,444]
for val in seq.windows(width:4) {
print(val)
}
extension Array {

func windows(width: Int) -> AnySequence<ArraySlice<Element>> {
return AnySequence({ () -> AnyIterator<ArraySlice<Element>> in
var index = self.startIndex

return AnyIterator({
if index > self.count - width {
return nil
}

let result = self[index..<index + width]

self.formIndex(after: &index)

return result
})
})
}

}

let seq = [1,11,333,33,5,623,123,44,7,444]
for val in seq.windows(width:4) {
print(val)
}
Want results from more Discord servers?
Add your server