Skip to content

Instantly share code, notes, and snippets.

@el-hoshino
Created December 8, 2023 13:21
Show Gist options
  • Save el-hoshino/f3242c5ad05ff208b0d680c8dc9c4299 to your computer and use it in GitHub Desktop.
Save el-hoshino/f3242c5ad05ff208b0d680c8dc9c4299 to your computer and use it in GitHub Desktop.
Collection Interpolation in Swift
extension Collection {
func interpolated(by interpolation: (_ previous: Element, _ current: Element) throws -> Element) rethrows -> [Element] {
var iterator = makeIterator()
var result = [Element]()
guard var previous = iterator.next() else {
return []
}
result.append(previous)
while let current = iterator.next() {
let interpolated = try interpolation(previous, current)
result.append(interpolated)
result.append(current)
previous = current
}
return result
}
}
@el-hoshino
Copy link
Author

Usage:

let a: [Double] = [1, 2, 3]
let b = a.interpolated { ($0 + $1) / 2 }
print(b) // [1.0, 1.5, 2.0, 2.5, 3.0]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment