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
Would a simple for-loop over the range be sufficiently readable and maintainable? You could just cache the intermediate values as you iterate, so that you only access one element of the array in each iteration. If you wanted to generalize this for any comparable type, you could implement it as an extension of Array:
extension Array where Element: Comparable {
func localMinimums() -> [Int] {
var minimums = [Int]()
var currentValue = self[0]
var nextValue = self[1]
for index in 1..<(self.count - 1) {
let previousValue = currentValue
currentValue = nextValue
nextValue = self[index + 1]
if currentValue < nextValue && currentValue < previousValue {
minimums.append(index)
}
}
return minimums
}
}
let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
let r = a.localMinimums()
print(r)
// [6, 11]