In Swift, I want to loop over an array and compare each element to the previous and/or next. For each comparison I will either produce a new element or nothing. Is there \"funct
I think Martin R's answer is smart, though I try answering using the other way.
let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
func withPrevAndNext(`default`: U, _ f: @escaping (T, T, T) -> (U)) -> (T) -> (U) {
var previous: T?
var current: T?
return { next in
defer { (previous, current) = (current, next) }
guard let prev = previous, let curt = current else { return `default` }
return f(prev, curt, next)
}
}
let r = a.enumerated().compactMap(withPrevAndNext(default: .none) { prev, curt, next -> Int? in
curt.1 < prev.1 && curt.1 < next.1 ? curt.0 : .none
})
print(r)
// [6, 11]