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

前端 未结 7 2584
庸人自扰
庸人自扰 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 14:53

    Using flatMap

    let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
    let r = a.enumerated().flatMap { (_ offset: Int, _ element: Int) -> Int? in
        guard offset > 0 else { return nil }
        if element < a[offset-1] && element < a[offset+1] {
            return offset
        }
        return nil
    }
    

提交回复
热议问题