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 could also iterate over indices and compare like this,
for i in a.indices.dropFirst().dropLast()
{
if a[i] < a[a.index(after: i)],
a[i] < a[a.index(before: i)] {
r.append(i)
}
}
print(r)
// [6, 11]
Or, something like this,
let result = a.indices.dropLast().dropFirst().filter { i in
return a[i] < a[a.index(after: i)] &&
a[i] < a[a.index(before: i)]
}
print(r)
// [6, 11]
Or, short,
let result = a.indices.dropLast()
.dropFirst()
.filter { a[$0] < a[$0 + 1] &&
a[$0] < a[$0 - 1] }
print(result)