Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
let xs = [0,1,2,3,4,5]
let double: (Int) -> Int = { $0 * 2 }
let isEven: (Int) -> Bool = { $0 % 2 == 0 }
// Goal: [0,2,4,6,4,10]. Double all but the last even element.
extension Collection {
func mapExceptLast(matching predicate: (Element) -> Bool, transform: (Element) -> Element) -> [Element] {
var result: [Element] = []
var lastMatch: (Element, Int)?
for element in self {
if predicate(element) {
lastMatch = (element, result.count)
}
result.append(transform(element))
}
// If we found a match, replace the last with untransformed element
if let (element, i) = lastMatch {
result[i] = element
}
return result
}
}
print(xs.mapExceptLast(matching: isEven, transform: double))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment