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

前端 未结 7 2462
庸人自扰
庸人自扰 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条回答
  •  -上瘾入骨i
    2021-02-20 15:00

    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)
    

提交回复
热议问题