Swift: loop over array elements and access previous and next elements

前端 未结 7 2583
庸人自扰
庸人自扰 2021-02-20 14:19

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

7条回答
  •  情深已故
    2021-02-20 15:06

    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]
    

提交回复
热议问题