Created
December 8, 2023 13:21
-
-
Save el-hoshino/f3242c5ad05ff208b0d680c8dc9c4299 to your computer and use it in GitHub Desktop.
Collection Interpolation in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: