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
You can replace the while
loop and i
with a for
loop and stride
.
let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
var r: [Int] = []
for i in stride(from: 1, to: a.count - 1, by: 1) {
if a[i] < a[i+1] && a[i] < a[i-1] {
r.append(i)
}
}
print(r)
// [6, 11]
You can get real fancy with a filter but this isn't nearly as readable as the above code:
let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
let r = a.enumerated().dropFirst().dropLast().filter { $0.1 < a[$0.0 + 1] && $0.1 < a[$0.0 - 1] }.map { $0.0 }
print(r)
// [6, 11]