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

前端 未结 7 2638
庸人自扰
庸人自扰 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:59

    I was looking for a variation of the original Q that I hope might help someone else. I needed to map every item in the array while considering the previous and next values:

    extension Sequence {
        var withPreviousAndNext: [(Element?, Element, Element?)] {
            let optionalSelf = self.map(Optional.some)
            let next = optionalSelf.dropFirst() + [nil]
            let prev = [nil] + optionalSelf.dropLast()
            return zip(self, zip(prev, next)).map {
                ($1.0, $0, $1.1)
            }
        }
    }
    

    And the not so pretty way to use that with original Q:

    let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
    let indices = a.enumerated().withPreviousAndNext.compactMap { values -> Int? in
        let (prev, cur, next) = values
        return (cur.1 < (prev?.1 ?? Int.min) && cur.1 < (next?.1 ?? Int.min)) ? cur.0 : nil
    }
    indices // [6,11]
    

提交回复
热议问题